forked from ronijpandey/Java-Codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra.java
104 lines (59 loc) · 2.17 KB
/
Dijkstra.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package javacodes;
import java.util.*;
public class Dijkstra {
static int V;
int minDistance(int dist[], Boolean que[])
{
int min = Integer.MAX_VALUE, index=-1;
for (int i = 0; i < V; i++)
if (que[i] == false && dist[i] <= min)
{
min = dist[i];
index = i;
}
return index;
}
void printSolution(int dist[], int n)
{
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i+" \t\t "+dist[i]);
}
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V];
Boolean que[] = new Boolean[V];
for (int i = 0; i < V; i++)
{
dist[i] = Integer.MAX_VALUE;
que[i] = false;
}
dist[src] = 0;
for (int count = 0; count < V-1; count++)
{
int u = minDistance(dist, que);
que[u] = true;
for (int i = 0; i < V; i++)
if (!que[i] && graph[u][i]!=0 &&
dist[u] != Integer.MAX_VALUE &&
dist[u]+graph[u][i] < dist[i])
dist[i] = dist[u] + graph[u][i];
}
printSolution(dist, V);
}
public static void main (String[] args)
{
Scanner in=new Scanner(System.in);
System.out.println("Number of vertices:");
V=in.nextInt();
int [][]graph = new int[V][V];
System.out.println("Rows and Column of matrix:");
for(int i=0;i<V;i++)
{
for(int j=0;j<V;j++)
graph[i][j]=in.nextInt();
}
Dijkstra ob=new Dijkstra();
ob.dijkstra(graph, 0);
}
}