-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDijkstra's Algorithm.java
77 lines (76 loc) · 1.38 KB
/
Dijkstra's Algorithm.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
import java.util.Scanner;
class Dijkstra_Algorithm
{
int v;
int g[][];
Dijkstra_Algorithm(int v)
{
this.v=v;
g=new int[v][v];
for(int i=0;i<v;i++)
{
for(int j=0;j<v;j++)
{
g[i][j]=0;
}
}
}
void addEdge(int src,int dest,int weight)
{
g[src][dest]=weight;
g[dest][src]=weight;
}
int minDist(int dist[],boolean memSet[])
{
int min=Integer.MAX_VALUE,minIndex=0;
for(int i=0;i<v;i++)
{
if(memSet[i]==false&&dist[i]<min)
{
min=dist[i];
minIndex=i;
}
}
return minIndex;
}
void dijkstra(int src)
{
int dist[]=new int[v];
boolean memSet[]=new boolean[v];
for(int i=0;i<v;i++)
{
dist[i]=Integer.MAX_VALUE;
memSet[i]=false;
}
dist[src]=0;
for(int i=0;i<v;i++)
{
int u=minDist(dist,memSet);
memSet[u]=true;
for(int j=0;j<v;j++)
{
if(memSet[j]==false&&g[u][j]!=0&&g[u][j]+dist[u]<dist[j]&&dist[u]!=Integer.MAX_VALUE)
dist[j]=g[u][j]+dist[u];
}
}
for(int i=0;i<v;i++)
{
System.out.println(i+"-->"+dist[i]);
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int v=sc.nextInt();
int e=sc.nextInt();
Dijkstra_Algorithm graph=new Dijkstra_Algorithm(v);
for(int i=1;i<=e;i++)
{
int src=sc.nextInt();
int dest=sc.nextInt();
int weight=sc.nextInt();
graph.addEdge(src,dest,weight);
}
int src=sc.nextInt();//Source Vertex.
graph.dijkstra(src);
}
}