0

I don't understand why we are increasing e += 1 when the parents are not same. And why the while loop stops based on e's value? Why we need that index?

def kruskal(self):
    i, e = 0, 0
    ds = dst.disjointSet(self.nodes)
    self.graph = sorted(self.graph, key=lambda graph:graph[2])
    while e < self.v - 1:   # vertices start from zero thats why -1
        s,d,w = self.graph[i]
        i += 1
        x = ds.findParent(s)
        y = ds.findParent(d)
        if x != y:
            e += 1
            self.MST.append([s,d,w])
            ds.union(x, y)
    self.printSolution()

ds is disjointSet's object where findParent and union methods are.

1 Answer 1

0

Variable e, I'd rather call it edges, represents a number of edges here. You may ask a question what is the mininum number of edges needed to connect n vertices? You can easily prove that's n - 1. So we iterate until we have a necessary number of edges to connect all vertices. We're checking parents x!=y to be sure there's no cycle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.