Repository navigation
Expand file tree
/
Copy pathGraphDijkstra.java
More file actions
65 lines (54 loc) · 1.75 KB
/
Copy pathGraphDijkstra.java
File metadata and controls
65 lines (54 loc) · 1.75 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
//Dijkstra Algorithm
import java.util.*;
public class GraphDijkstra{
private int adjMatrix[][];
private int vertexCount;
public GraphDijkstra(int vertices){
vertexCount = vertices;
adjMatrix = new int[vertices][vertices];
}
public void addEdge(int i, int j , int w){
adjMatrix[i][j] = w;
adjMatrix[j][i] = w;
}
public int minDistance(int dist[] , boolean visited[]){
int min = Integer.MAX_VALUE, minIndex = -1;
for(int v=0;v<vertexCount;v++){
if(!visited[v] && dist[v]<min){
min = dist[v];
minIndex = v;
}
}
return minIndex;
}
public int[] dijkstra(int graph[][],int sourceVertex){
int dist[] = new int[vertexCount];
boolean visited[] = new boolean[vertexCount];
Arrays.fill(dist,Integer.MAX_VALUE);
dist[sourceVertex]=0;
for(int i=0;i<vertexCount-1;i++){
int u = minDistance(dist,visited);
visited[u]=true;
for(int v=0;v<vertexCount;v++){
if(!visited[v] && graph[u][v]!=0 && dist[u]!=Integer.MAX_VALUE && dist[u]+graph[u][v]<dist[v]){
dist[v] = dist[u] + graph[u][v];
}
}
}
return dist;
}
public static void main(String args[]){
GraphDijkstra graph = new GraphDijkstra(5);
graph.addEdge(0,1,4);
graph.addEdge(1,4,6);
graph.addEdge(4,3,10);
graph.addEdge(3,2,2);
graph.addEdge(0,2,8);
int ans[] = new int[graph.vertexCount];
int sourceVertex = 4;
ans = graph.dijkstra(graph.adjMatrix, 4);
for(int i=0;i<graph.vertexCount;i++){
System.out.println(sourceVertex+" to "+i+": "+ans[i]);
}
}
}