-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.java
More file actions
76 lines (67 loc) · 2.22 KB
/
Dijkstra.java
File metadata and controls
76 lines (67 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.util.Random;;
public class Dijkstra{
private DirectedEdge[] edgeTo;
private double[] distTo;
private IndexMinPQ<Double> pq;
public Dijkstra(EdgeWeightDigraph G,int s){
edgeTo=new DirectedEdge[G.V()];
distTo=new double[G.V()];
pq=new IndexMinPQ<>(G.V());
for (int i=0;i<G.V();i++){
distTo[i]=Double.POSITIVE_INFINITY;
}
distTo[s]=0.0;
pq.insert(s, 0.0);
while (!pq.isEmpty()){relax(G,pq.delMin());}
}
private void relax(EdgeWeightDigraph G, int v){
for (DirectedEdge edge:G.adj(v)){
int w=edge.to();
if (distTo[w]>distTo[v]+edge.weight()){
distTo[w]=distTo[v]+edge.weight();
edgeTo[w]=edge;
}
if (pq.contains(w)) pq.replace(w,distTo[w]);
else pq.insert(w, distTo[w]);
}
}
public double distTo(int v){return distTo[v];}
public boolean hasPathTo(int v){return distTo(v)<Double.POSITIVE_INFINITY;}
public Iterable<DirectedEdge> pathTo(int v){
if (!hasPathTo(v)) return null;
Stack<DirectedEdge> st=new Stack<>();
for (DirectedEdge edge=edgeTo[v];edge!=null;edge=edgeTo[edge.from()]){
st.push(edge);
}
return st;
}
public String showMinTree(int v){
String s="";
for (DirectedEdge edge:this.pathTo(v)){
s+=edge+"\n";
}
return s;
}
public double weight(int v){
double weight=0.0;
for (DirectedEdge edge:this.pathTo(v)){
weight+=edge.weight();
}
return weight;
}
public static void main(String[] args){
Random r = new Random();
int V=6;
EdgeWeightDigraph g=new EdgeWeightDigraph(V);
for (int i=0;i<V;i++){
int w=r.nextInt(V-1);
int v=r.nextInt(V-1);
double weight=r.nextDouble();
DirectedEdge edge=new DirectedEdge(w,v,weight);
g.addEdge(edge);
}
Dijkstra dijkstra=new Dijkstra(g,0);
System.out.println(dijkstra.hasPathTo(5));
//System.out.println(dijkstra.weight(5));
}
}