|
13 | 13 | Time Complexity : O(ElogV) |
14 | 14 | """ |
15 | 15 |
|
16 | | -from dataclasses import dataclass |
17 | 16 |
|
18 | | -@dataclass(eq=0) |
19 | | -class Node: |
20 | | - _num : int |
| 17 | +# @dataclass(eq=0) |
21 | 18 |
|
22 | | -@dataclass |
23 | | -class Graph: |
24 | | - source : int |
25 | | - _list : dict |
| 19 | + |
| 20 | +class Node(object): |
| 21 | + def __init__(self, source=None): |
| 22 | + self._num = source |
| 23 | + |
| 24 | + |
| 25 | +class Prims(object): |
| 26 | + def __init__(self, source, graph): |
| 27 | + self.source = source |
| 28 | + self._list = graph |
26 | 29 |
|
27 | 30 | def prims_MCST(self): |
28 | 31 | MCST_Cost = 0 |
29 | | - queue = {Node(self.source) : 0} |
| 32 | + queue = {Node(self.source): 0} |
30 | 33 | added = [0]*len(self._list) |
31 | 34 |
|
32 | 35 | while queue: |
33 | | - node = min(queue,key=queue.get)#choosing the adjancent Node having the minimum cost |
| 36 | + # choosing the adjancent Node having the minimum cost |
| 37 | + node = min(queue, key=queue.get) |
34 | 38 | cost_Node = queue[node] |
35 | | - #Delete that Node from the Dict |
| 39 | + # Delete that Node from the Dict |
36 | 40 | del queue[node] |
37 | 41 |
|
38 | | - if added[node._num] == 0: #If node is not Visited |
39 | | - MCST_Cost+=cost_Node |
40 | | - |
41 | | - added[node._num] = True #Mark Visited |
| 42 | + if added[node._num] == 0: # If node is not Visited |
| 43 | + MCST_Cost += cost_Node |
42 | 44 |
|
43 | | - print(f"{node._num} --> ",end=" ") |
| 45 | + added[node._num] = True # Mark Visited |
44 | 46 |
|
| 47 | + print(f"{node._num} --> ", end=" ") |
45 | 48 |
|
46 | 49 | for n in self._list[node._num]: |
47 | 50 | adjancent_node = n[0] |
48 | 51 | adjancent_cost = n[1] |
49 | 52 | if added[adjancent_node] == 0: |
50 | 53 | queue[Node(adjancent_node)] = adjancent_cost |
51 | | - print("Cost : ",MCST_Cost) |
| 54 | + print("Cost : ", MCST_Cost) |
52 | 55 |
|
53 | 56 |
|
54 | 57 | if __name__ == '__main__': |
55 | 58 | list = {} |
56 | | - list[1]=[(6,10),(2,28)] |
57 | | - list[2]=[(1,28),(3,16),(0,14)] |
58 | | - list[3]=[(2,16),(4,12)] |
59 | | - list[4]=[(3,12),(5,22),(0,18)] |
60 | | - list[5]=[(4,22),(6,25),(0,24)] |
61 | | - list[6]=[(1,10),(5,25)] |
62 | | - list[0]=[(2,14),(4,18),(5,24)] |
63 | | - |
64 | | - A = Graph(3,list) #Insert Any Node |
| 59 | + list[1] = [(6, 10), (2, 28)] |
| 60 | + list[2] = [(1, 28), (3, 16), (0, 14)] |
| 61 | + list[3] = [(2, 16), (4, 12)] |
| 62 | + list[4] = [(3, 12), (5, 22), (0, 18)] |
| 63 | + list[5] = [(4, 22), (6, 25), (0, 24)] |
| 64 | + list[6] = [(1, 10), (5, 25)] |
| 65 | + list[0] = [(2, 14), (4, 18), (5, 24)] |
| 66 | + |
| 67 | + A = Prims(3, list) # Insert Any Node |
65 | 68 | print("MCST") |
66 | 69 | A.prims_MCST() |
67 | | - |
68 | | - |
69 | | - |
70 | | - |
71 | | - |
72 | | - |
73 | | - |
74 | | - |
75 | | - |
76 | | - |
77 | | - |
78 | | - |
0 commit comments