Uploaded by Sanika Chaudhari

Kruskals Algorithm Code

advertisement
Assignment 3:
class Graph:
def _init_(self, num_vertices):
self.num_vertices = num_vertices
self.adjacency_list = {v: [] for v in range(num_vertices)}
self.edges = []
def add_edge(self, v1, v2, weight):
self.adjacency_list[v1].append((v2, weight))
self.adjacency_list[v2].append((v1, weight))
self.edges.append((v1, v2, weight))
def kruskal(self):
self.edges.sort(key=lambda x: x[2])
parent = list(range(self.num_vertices))
rank = [0] * self.num_vertices
result = []
def find(v):
if parent[v] != v:
parent[v] = find(parent[v])
return parent[v]
def union(v1, v2):
root1 = find(v1)
root2 = find(v2)
if root1 != root2:
if rank[root1] > rank[root2]:
parent[root2] = root1
elif rank[root1] < rank[root2]:
parent[root1] = root2
else:
parent[root2] = root1
rank[root1] += 1
for edge in self.edges:
v1, v2, weight = edge
if find(v1) != find(v2):
result.append(edge)
union(v1, v2)
return result
def create_graph_from_user():
num_vertices = int(input("Enter the number of vertices in the graph: "))
num_edges = int(input("Enter the number of edges in the graph: "))
graph = Graph(num_vertices)
for _ in range(num_edges):
v1, v2, weight = map(int, input("Enter edge and weight (vertex1 vertex2 weight):
").split())
graph.add_edge(v1, v2, weight)
return graph
# Example usage:
graph = create_graph_from_user()
print("Graph created with adjacency list:", graph.adjacency_list)
print("Minimum Spanning Tree (MST) using Kruskal's algorithm:", graph.kruskal())
Output:
Enter the number of vertices in the graph: 3
Enter the number of edges in the graph: 3
Enter edge and weight (vertex1 vertex2 weight): 0 1 2
Enter edge and weight (vertex1 vertex2 weight): 1 2 6
Enter edge and weight (vertex1 vertex2 weight): 0 2 1
Graph created with adjacency list: {0: [(1, 2), (2, 1)], 1: [(0, 2), (2, 6)], 2: [(1, 6), (0, 1)]}
Minimum Spanning Tree (MST) using Kruskal's algorithm: [(0, 2, 1), (0, 1, 2)]
=== Code Execution Successful ===
Download