Facebook Pixel

Prim's MST Algorithm

JavaScript
hard
45 mins

Given a weighted undirected graph represented as an adjacency list, return the sum of weights of the edges in the Minimum Spanning Tree.

Examples

Input: 
graph = [
  [[2,1], [4,2]],          // Node 0 is connected to 1 (wt 2) and 2 (wt 4)
  [[2,0], [1,2], [3,3]],   // Node 1 is connected to 0 (wt 2), 2 (wt 1), 3 (wt 3)
  [[4,0], [1,1], [5,3]],   // Node 2 is connected to 0 (wt 4), 1 (wt 1), 3 (wt 5)
  [[3,1], [5,2]]           // Node 3 is connected to 1 (wt 3), 2 (wt 5)
]
Output: 6

Input:
graph = [
  [[1, 1], [5, 2]],
  [[1, 0], [2, 2]],
  [[5, 0], [2, 1]]
]
Output: 3

Input:
graph = [[]]
Output: 0

Constraints

  • The graph is connected.
  • Weights are non-negative integers.
  • Number of nodes V <= 1000.
  • Number of edges E <= 10000.

Companies:

DP World
Tekion
linkedin

Solve Similar questions 🔥

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.