Skip to content

Commit c857f86

Browse files
author
Hamid Gasmi
committed
Issue #136 is completed with Prim's Algorithm
1 parent 2b97ba9 commit c857f86

File tree

4 files changed

+45
-3
lines changed

4 files changed

+45
-3
lines changed

3-graph-algorithms/3_spanning_trees/clustering.py

-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ def clustering(x, y, k):
66
#write your code here
77
return -1.
88

9-
109
if __name__ == '__main__':
1110
input = sys.stdin.read()
1211
data = list(map(int, input.split()))

3-graph-algorithms/3_spanning_trees/connecting_points.py

+34-2
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,44 @@
11
#Uses python3
22
import sys
33
import math
4+
import queue
5+
from collections import namedtuple
6+
7+
Point = namedtuple('Point', ['len', 'x', 'y', 'index'])
48

59
def minimum_distance(x, y):
10+
11+
n = len(x)
12+
visited = [False] * n
13+
parents = [-1] * n
14+
15+
infinity = 3 * 10**3
16+
distances = [infinity] * n
17+
distances[0] = 0
18+
19+
hq = queue.PriorityQueue()
20+
for i in range(1, n):
21+
hq.put(Point(infinity, x[i], y[i], i))
22+
hq.put(Point(0, x[0], y[0], 0))
23+
24+
while not hq.empty():
25+
p = hq.get()
26+
visited[p.index] = True
27+
#print("(i, x, y, distances): ", p.index, p.x, p.y, distances)
28+
#print("hq.empty", "empty" if hq.empty() else "not empty")
29+
for i in range(n):
30+
if not visited[i]:
31+
candidate_distance = math.sqrt((p.x - x[i])**2 + (p.y - y[i])**2)
32+
if distances[i] > candidate_distance:
33+
distances[i] = candidate_distance
34+
parents[i] = p.index
35+
hq.put(Point(distances[i], x[i], y[i], i))
36+
637
result = 0.
7-
#write your code here
8-
return result
38+
for d in distances:
39+
result += d
940

41+
return result
1042

1143
if __name__ == '__main__':
1244
input = sys.stdin.read()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
4
2+
0 0
3+
0 1
4+
1 0
5+
1 1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
5
2+
0 0
3+
0 2
4+
1 1
5+
3 0
6+
3 2

0 commit comments

Comments
 (0)