This repository was archived by the owner on Jun 2, 2024. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
C++/Algorithms/GreedyAlgorithms Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+
3
+ using namespace std ;
4
+
5
+ int miniDist (int distance[], bool Tset[],int m,int n) // finding minimum distance
6
+ {
7
+ int minimum=INT_MAX,ind;
8
+
9
+ for (int k=0 ;k<m;k++)
10
+ {
11
+ if (Tset[k]==false && distance[k]<=minimum)
12
+ {
13
+ minimum=distance[k];
14
+ ind=k;
15
+ }
16
+ }
17
+ return ind;
18
+ }
19
+
20
+ void DijkstraAlgo (int m, int n,int graph[][20 ],int src) // adjacency matrix
21
+ {
22
+ int distance[m]; // // array to calculate the minimum distance for each node
23
+ bool Tset[n];// boolean array to mark visited and unvisited for each node
24
+
25
+
26
+ for (int k = 0 ; k<m; k++)
27
+ {
28
+ distance[k] = INT_MAX;
29
+ Tset[k] = false ;
30
+ }
31
+
32
+ distance[src] = 0 ; // Source vertex distance is set 0
33
+
34
+ for (int k = 0 ; k<m; k++)
35
+ {
36
+ int mn=miniDist (distance,Tset,m,n);
37
+ Tset[mn]=true ;
38
+ for (int k = 0 ; k<m; k++)
39
+ {
40
+ // updating the distance of neighbouring vertex
41
+ if (!Tset[k] && graph[mn][k] && distance[mn]!=INT_MAX && distance[mn]+graph[mn][k]<distance[k])
42
+ distance[k]=distance[mn]+graph[mn][k];
43
+ }
44
+ }
45
+ cout<<" Vertex\t\t Distance from source vertex" <<endl;
46
+ for (int k = 0 ; k<m; k++)
47
+ {
48
+ char str=65 +k;
49
+ cout<<str<<" \t\t\t " <<distance[k]<<endl;
50
+ }
51
+ }
52
+
53
+ int main ()
54
+
55
+ { int m,n;
56
+ cin>>m>>n;
57
+ int graph[20 ][20 ];
58
+ for (int i=0 ;i<m;i++){
59
+ for (int j=0 ;j<m;j++){
60
+ cin>>graph[i][j];
61
+ }
62
+ }
63
+ DijkstraAlgo (m,n,graph,0 );
64
+ return 0 ;
65
+ }
You can’t perform that action at this time.
0 commit comments