0

I am trying to implement Prim's algorithm but the output changes every time I run it

{'A': {'C'}, 'B': {'A'}, 'F': {'G'}, 'E': {'B'}, 'D': {'E'}, 'C': {'F'}}

when it is supposed to be

{'D': {'E'}, 'E': {'B'}, 'B': {'A'}, 'A': {'C'}, 'C': {'F'}, 'F': {'G'}}

Not sure what exactly is going on here, I tried debugging to no avail. Does anyone know if I am missing something glaringly obvious?

from collections import defaultdict
import heapq


def create_spanning_tree(graph, starting_vertex):
    mst = defaultdict(set)
    visited = set([starting_vertex])
    edges = [
        (cost, starting_vertex, to)
        for to, cost in graph[starting_vertex].items()
    ]
    heapq.heapify(edges)
    while edges:
        cost, frm, to = heapq.heappop(edges)
        if to not in visited:
            visited.add(to)
            mst[frm].add(to)
            for to_next, cost in graph[to].items():
                if to_next not in visited:
                    heapq.heappush(edges, (cost, to, to_next))
    return mst

example_graph = {
    'A': {'B': 2, 'C': 3},
    'B': {'A': 2, 'C': 12, 'D': 10, 'E': 4},
    'C': {'A': 3, 'B': 12, 'F': 5},
    'D': {'B': 10, 'E': 7},
    'E': {'B': 4, 'D': 7, 'F': 16},
    'F': {'C': 5, 'E': 16, 'G': 9},
    'G': {'F': 9},
}
print(dict(create_spanning_tree(example_graph, 'D')))

1 Answer 1

1

Looking closely at both the outputs,

{'A': {'C'}, 'B': {'A'}, 'F': {'G'}, 'E': {'B'}, 'D': {'E'}, 'C': {'F'}} and {'D': {'E'}, 'E': {'B'}, 'B': {'A'}, 'A': {'C'}, 'C': {'F'}, 'F': {'G'}} are same.

Since it's a dictionary, (key, value) pairs matter, which is same in both the answers and not the order in which they appear.

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.