DSA SectionEasy

Prim

Detailed guide and Python implementation for the 'Prim' problem.

Problem Statement

Easy

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.

Constraints
  • 1 <= V <= 500
  • 0 <= E <= 1000

Examples

Example 1
Input
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}}
Output
16
Explanation

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?
Consider using Graphs-specific data structures like sets or heaps.
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.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.