我想遍历一个图,并与一个队列值进行比较,如果它存在的话。
我想把这段Python代码真正实现到java中去
遍历当前节点
for it in gr[curr] :
iin f it not in pq :
pq.insert(0,( dist * it[1], it[0] ));
这里,gr是一个图,pq是一个队列数组,dist是int变量。
实际上,我想在java中实现这个------。
https:/www.geeksforgeeks.orgpath-with-smallest-product-of-edges-with-weight-1
这是我的完整代码,到目前为止-
package com.company;
import java.util.*;
public class solution {
public static int dijkstra(int s, int d, ArrayList<ArrayList<Integer>>graph) {
if (s == d) return 0;
ArrayList<ArrayList<Integer>> queue = new ArrayList<>(10);
for(int i=0; i < 10 ; i++) {
ArrayList<Integer> sublist = new ArrayList<>(10);
sublist.add(0);
queue.add(sublist);
}
queue.get(0).add(1);
boolean[] v = {false};
while (!queue.isEmpty()) {
int curr = queue.get(0).get(1);
int dist = queue.get(0).get(0);
queue.remove(curr);
if (v[curr])
continue;
v[curr] = true;
if (curr == d)
return dist;
Iterator<ArrayList<Integer>> iter = graph.iterator();
while (iter.hasNext())
{
queue.add()\\not completed
}
}
return -1;
}
public static void main(String[]args)
{
int n = 3;
ArrayList<ArrayList<Integer>> graph = new ArrayList<>(n+2);
for(int i=0; i < n+2 ; i++) {
ArrayList<Integer> list = new ArrayList<>();
for(int j = 0; j< n+2; j++){
list.add(0);
}
graph.add(list);
}
graph.get(1).add(3,9);
graph.get(2).add(3,1);
graph.get(1).add(2,5);
int s = 1, d = 3;
System.out.println(dijkstra(s,d,graph));
}
}
在这里,你应该创建 Edge
类和使用 PriorityQueue
遥相呼应
public static int dijkstra(int s, int d, ArrayList<ArrayList<Edge>> graph) {
if (s == d)
return 0;
PriorityQueue<Edge> queue = new PriorityQueue<>();
queue.add(new Edge(1, s));
boolean[] v = new boolean[graph.size()];
v[s] = false;
while (!queue.isEmpty()) {
Edge edge = queue.poll();
if (v[edge.vertex])
continue;
v[edge.vertex] = true;
int dist = edge.dist;
if (edge.vertex == d)
return dist;
if (graph.size() >= edge.vertex)
for (Edge e : graph.get(edge.vertex)) {
if (!queue.contains(e)) {
queue.add(new Edge(dist * e.vertex, e.dist));
}
}
}
return -1;
}
public static void main(String[] args) {
int n = 3;
ArrayList<ArrayList<Edge>> graph = new ArrayList<>();
for (int i = 0; i <= n + 1; i++) {
graph.add(new ArrayList<>());
}
graph.get(1).add(new Edge(3, 9));
graph.get(2).add(new Edge(3, 1));
graph.get(1).add(new Edge(2, 5));
int s = 1, d = 3;
System.out.println(dijkstra(s, d, graph));
}
static class Edge implements Comparable<Edge> {
int vertex;
int dist;
public Edge(int dist, int vertex) {
this.dist = dist;
this.vertex = vertex;
}
@Override
public int compareTo(Edge o) {
return Integer.valueOf(this.dist).compareTo(Integer.valueOf(o.dist));
}
@Override
public String toString() {
return dist + ", " + vertex;
}
}