Skip to content

Commit 6b40fe3

Browse files
authored
Create Dijkstra's Algorithm
1 parent 563a505 commit 6b40fe3

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Dijkstra's Algorithm

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
public class Main {
2+
public static void main(String[] args) {
3+
int noOfVertices = 5;
4+
int startVertex=0; // A is start vertex
5+
6+
List<Pair<Integer,Integer>>[] adj=new ArrayList[noOfVertices];
7+
8+
//Pair(vertex, weight)
9+
List<Pair<Integer,Integer>> list=new ArrayList<>();
10+
list.add(new Pair(1,4));
11+
list.add(new Pair(2,1));
12+
adj[0]=list;
13+
14+
list=new ArrayList<>();
15+
list.add(new Pair(4,4));
16+
adj[1]=list;
17+
18+
list=new ArrayList<>();
19+
list.add(new Pair(1,2));
20+
list.add(new Pair(3,4));
21+
adj[2]=list;
22+
23+
list=new ArrayList<>();
24+
list.add(new Pair(4,4));
25+
adj[3]=list;
26+
27+
list=new ArrayList<>();
28+
adj[4]=list;
29+
30+
int[] path = new int[noOfVertices];
31+
int[] distance = new int[noOfVertices];
32+
33+
Arrays.fill(distance,-1); // Intialize distance array
34+
35+
distance[startVertex]=0; // Making distance for start vertex 0
36+
path[startVertex]=startVertex; // Updating path for start vertex to itself
37+
38+
PriorityQueue<Pair<Integer,Integer>> q=new PriorityQueue<>((a,b) -> a.getValue()-b.getValue());
39+
q.add(new Pair<>(startVertex,0));
40+
41+
while(!q.isEmpty()){
42+
Pair<Integer,Integer> vertexPair=q.remove();
43+
Integer vertex=vertexPair.getKey();
44+
45+
List<Pair<Integer,Integer>> adjVertices=adj[vertex];
46+
47+
for(Pair<Integer,Integer> adjPair: adjVertices){
48+
int adjVertex=adjPair.getKey();
49+
int weight=adjPair.getValue();
50+
51+
int newDistance=distance[vertex] + weight;
52+
if(distance[adjVertex]==-1 || distance[adjVertex]>newDistance){
53+
distance[adjVertex]=newDistance;
54+
path[adjVertex]=vertex;
55+
q.add(new Pair<>(adjVertex,distance[adjVertex]));
56+
}
57+
}
58+
}
59+
60+
System.out.println("Distance from "+(char)(startVertex+'A')+" :");
61+
for(int i=0;i<noOfVertices; i++){
62+
System.out.print("Distance to "+(char)(i+'A')+" is "+distance[i]);
63+
System.out.println(" from path "+(char)(path[i]+'A'));
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)