-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathKruskal_Algorithm.dart
159 lines (130 loc) · 2.99 KB
/
Kruskal_Algorithm.dart
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/*
Kruskal's algorithm is a minimum spanning tree algorithm that takes a graph a
s input and finds the subset of the edges of that graph which
(1) form a tree that includes every vertex
(2) has the minimum sum of weights among all the trees that can be
formed from the graph
*/
import 'dart:io';
var INT_MAX = 9223372036854775807;
int find(i, parent)
{
while (parent[i] != i) {
i = parent[i];
}
return i;
}
void union1(i, j, parent)
{
var a = find(i, parent);
var b = find(j, parent);
parent[a] = b;
}
void kruskal_mst(adjmat, V)
{
var mincost = 0;
var parent = new List(V);
for (var i = 0; i < V; i++)
{
parent[i] = i;
}
var edge_count = 0;
while (edge_count < V - 1)
{
var min = INT_MAX, a = -1, b = -1;
for (var i = 0; i < V; i++)
{
for (var j = 0; j < V; j++)
{
if (find(i, parent) != find(j, parent) && adjmat[i][j] < min)
{
min = adjmat[i][j];
a = i;
b = j;
}
}
}
union1(a, b, parent);
print('Edge ${edge_count++}:(${a}, ${b}) cost:${min} \n');
mincost += min;
}
print('\n Minimum cost= ${mincost} \n');
}
int main()
{
print('Enter number of nodes 0 to ?');
var n = int.parse(stdin.readLineSync());
var max_edges = (n + 1) * (n);
var adjmat = new List.generate(n+1, (_) => new List(n + 1));
for(var i = 0; i <= n; i++)
{
for(var j = 0; j <= n; j++)
{
adjmat[i][j] = INT_MAX;
}
}
print('Enter in the following format\nsrc\ndest\nweight\n');
for(var i = 0; i < max_edges; i++)
{
var src = int.parse(stdin.readLineSync());
var dest = int.parse(stdin.readLineSync());
var weight = int.parse(stdin.readLineSync());
print('*' * 20);
if((src == -1) && (dest == -1))
{
break;
}
if(src > n || dest > n || src < 0 || dest < 0)
{
print('Invalid edge!\n');
i--;
}
else
{
adjmat[src][dest] = weight;
}
}
kruskal_mst(adjmat , n + 1);
return 0;
}
/*
Input:
Enter number of nodes 0 to ?
4
Enter in the following format
Source
Destination
Weight
Let the given graph is :
(1)____1___(2)
/ \ / \
3 4 4 6
/ \ / \
/ \ / \
(0)___5___(5)____5___(3)
\ | /
\ | /
\ | /
\ 2 /
6 | 8
\ | /
\ | /
\ | /
\ | /
(4)
adjmat = [
[ 0, 3, 0, 0, 6, 5 ],
[ 3, 0, 1, 0, 0, 4 ],
[ 0, 1, 0, 6, 0, 4 ],
[ 0, 0, 6, 0, 8, 5 ],
[ 6, 0, 0, 8, 0, 2 ],
[ 5, 4, 4, 5, 2, 0 ]
];
Output:
Edge: 0-1 cost: 3
Edge: 1-2 cost: 1
Edge: 1-5 cost: 4
Edge: 5-4 cost: 2
Edge: 5-3 cost: 5
Minimum Weight is 15
*/