-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKrushkals_Algorithm.cpp
More file actions
61 lines (51 loc) · 1.46 KB
/
Copy pathKrushkals_Algorithm.cpp
File metadata and controls
61 lines (51 loc) · 1.46 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
#include <bits/stdc++.h>
using namespace std;
#define INF 9999999
#define V 5
int graph[V][V] = {{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}};
// int minimumVertex(vector<int> &distance, vector<int> &visited)
// {
// int minEdge = INF;
// int result = -1;
// for (int i = 0; i < V; i++)
// {
// if (distance[i] < minEdge and visited[i] == 0)
// {
// minEdge = distance[i];
// result = i;
// }
// }
// return result;
// }
void KrushkalsAlgorithm(vector<int> &distance, vector<int> &parent, int source)
{
int edges = 0;
distance[source] = 0;
while (edges < V - 1)
{
for (int i = 1; i < V; i++)
for (int j = 1; j <= V; j++)
if (graph[i][j] != 0 and (graph[i][j] < distance[j]))
{
distance[j] = graph[i][j];
parent[j] = j;
}
edges++;
}
for (int i = 1; i <= V; i++)
cout << "\nDistance of " << source << " to " << i << " is : " << distance[i];
for (int i = 0; i < V; i++)
cout << "Parent of " << i << " is : " << parent[i] << " and Distance : " << distance[i] << endl;
}
int main()
{
vector<int> distance(V, INF);
vector<int> parent(V, -1);
//vector<int> visited(V, 0);
KrushkalsAlgorithm(distance, parent, 0);
return 0;
}