Skip to content

Commit 89f15be

Browse files
dunderbrunoAnupKumarPanwar
authored andcommitted
Create prim.py (TheAlgorithms#397)
1 parent 5be32f4 commit 89f15be

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

Graphs/prim.py

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
"""
2+
Prim's Algorithm.
3+
4+
Determines the minimum spanning tree(MST) of a graph using the Prim's Algorithm
5+
6+
Create a list to store x the vertices.
7+
G = [vertex(n) for n in range(x)]
8+
9+
For each vertex in G, add the neighbors:
10+
G[x].addNeighbor(G[y])
11+
G[y].addNeighbor(G[x])
12+
13+
For each vertex in G, add the edges:
14+
G[x].addEdge(G[y], w)
15+
G[y].addEdge(G[x], w)
16+
17+
To solve run:
18+
MST = prim(G, G[0])
19+
"""
20+
21+
import math
22+
23+
24+
class vertex():
25+
"""Class Vertex."""
26+
27+
def __init__(self, id):
28+
"""
29+
Arguments:
30+
id - input an id to identify the vertex
31+
32+
Attributes:
33+
neighbors - a list of the vertices it is linked to
34+
edges - a dict to store the edges's weight
35+
"""
36+
self.id = str(id)
37+
self.key = None
38+
self.pi = None
39+
self.neighbors = []
40+
self.edges = {} # [vertex:distance]
41+
42+
def __lt__(self, other):
43+
"""Comparison rule to < operator."""
44+
return (self.key < other.key)
45+
46+
def __repr__(self):
47+
"""Return the vertex id."""
48+
return self.id
49+
50+
def addNeighbor(self, vertex):
51+
"""Add a pointer to a vertex at neighbor's list."""
52+
self.neighbors.append(vertex)
53+
54+
def addEdge(self, vertex, weight):
55+
"""Destination vertex and weight."""
56+
self.edges[vertex.id] = weight
57+
58+
59+
def prim(graph, root):
60+
"""
61+
Prim's Algorithm.
62+
63+
Return a list with the edges of a Minimum Spanning Tree
64+
65+
prim(graph, graph[0])
66+
"""
67+
A = []
68+
for u in graph:
69+
u.key = math.inf
70+
u.pi = None
71+
root.key = 0
72+
Q = graph[:]
73+
while Q:
74+
u = min(Q)
75+
Q.remove(u)
76+
for v in u.neighbors:
77+
if (v in Q) and (u.edges[v.id] < v.key):
78+
v.pi = u
79+
v.key = u.edges[v.id]
80+
for i in range(1, len(graph)):
81+
A.append([graph[i].id, graph[i].pi.id])
82+
return(A)

0 commit comments

Comments
 (0)