From 4d7c16e0f10f7812efb7a00428c53bed56d9b63c Mon Sep 17 00:00:00 2001 From: Ayushi Sharma <51323447+Ayu-99@users.noreply.github.com> Date: Sat, 3 Oct 2020 13:09:35 +0530 Subject: [PATCH 1/2] Prims Algorithm --- Prims Algorithm | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Prims Algorithm diff --git a/Prims Algorithm b/Prims Algorithm new file mode 100644 index 0000000..ebfd8ab --- /dev/null +++ b/Prims Algorithm @@ -0,0 +1,43 @@ + +def findMinVertex(weights,n,visited): + minVertex=-1 + for i in range(n): + if not visited[i] and (minVertex==-1 or weights[i] Date: Sat, 3 Oct 2020 13:13:16 +0530 Subject: [PATCH 2/2] Kruskals aLgorithm --- Kruskals Algorithm | 53 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Kruskals Algorithm diff --git a/Kruskals Algorithm b/Kruskals Algorithm new file mode 100644 index 0000000..3e8b1da --- /dev/null +++ b/Kruskals Algorithm @@ -0,0 +1,53 @@ + + +class Edge: + def __init__(self): + self.src = 0 + self.dest = 0 + self.weight = 0 + + +def findParent(src, parent): + if parent[src] == 0: + return src + return findParent(parent[src], parent) + + +def kruskals(edges, n, e): + edges.sort(key=lambda edge: edge.weight) + edge = Edge() + output = [edge] * (n - 1) # n-1 edges + parent = [0] * (n) + + count = 0 + i = 0 + while count != (n - 1): + currentEdge = edges[i] + srcp = findParent(currentEdge.src, parent) + destp = findParent(currentEdge.dest, parent) + if srcp != destp: + output[count] = currentEdge + count += 1 + parent[srcp] = destp + i += 1 + + print("MST is:") + for i in range(n - 1): + print(output[i].src, "+", output[i].dest, "+", output[i].weight) + + +n = int(input("Enter number of vertices")) +e = int(input("Enter number of edges")) + +edge = Edge() +edges = [edge] * e + +for i in range(e): + src, dest, weight = map(int, input().split()) + edge1 = Edge() + edge1.src = src + edge1.dest = dest + edge1.weight = weight + edges[i] = edge1 + +kruskals(edges, n, e)