-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Simplified implementation of Minimum spanning tree using Kruskal’s Al…
…gorithm
- Loading branch information
1 parent
85168d6
commit 9a0538c
Showing
2 changed files
with
33 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
# -*- coding: utf-8 -*- | ||
"""Minimum spanning tree using Kruskal’s Algorithm""" | ||
|
||
from structures.disjoint_set import DSet | ||
|
||
|
||
if __name__ == '__main__': | ||
# Format: (node P, node Q, distance) | ||
# https://he-s3.s3.amazonaws.com/media/uploads/6322896.jpg | ||
g = [ | ||
('A', 'B', 1), | ||
('A', 'C', 7), | ||
|
||
('B', 'C', 5), | ||
('B', 'D', 4), | ||
('B', 'E', 3), | ||
|
||
('C', 'E', 6), | ||
('D', 'E', 2), | ||
] | ||
|
||
dset = DSet(['A', 'B', 'C', 'D', 'E']) | ||
mst = [] | ||
for p, q, distance in sorted(g, key=lambda item: item[2]): | ||
print('--> %s' % ([p, q, distance])) | ||
if dset.connected(p, q): | ||
print('Cycle detected') | ||
continue | ||
dset.union(p, q) | ||
mst.append((p, q, distance)) | ||
|
||
assert mst == [('A', 'B', 1), ('D', 'E', 2), ('B', 'E', 3), ('B', 'C', 5)] |
9a0538c
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Solves #2