Prim
Detailed guide and Python implementation for the 'Prim' problem.
Problem Statement
Write a function prim_mst(graph) that takes an undirected, connected, weighted graph represented as an adjacency list of dictionaries (where graph[u][v] is the weight of edge (u, v)) and returns the sum of weights of the Minimum Spanning Tree (MST) using Prim's algorithm.
- •1 <= V <= 500
- •0 <= E <= 1000
Examples
graph = {0: {1: 2, 3: 6}, 1: {0: 2, 2: 3, 3: 8, 4: 5}, 2: {1: 3, 4: 7}, 3: {0: 6, 1: 8, 4: 9}, 4: {1: 5, 2: 7, 3: 9}}16
MST edges selected are: (0,1) wt 2, (1,2) wt 3, (1,4) wt 5, (0,3) wt 6. Total weight = 16.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.