Facebook Pixel

Minimum Cost to Visit Every Node

Problem Statement

Prereq: Bitmask Introduction

Given a directed weighted graph as a 2D list where graph[i][j] is the edge weight from node i to j (0 means no edge), find the minimum cost to visit every node starting from node 0. You must visit each node exactly once (revisiting nodes is not allowed), and you don't need to return to the start. Return -1 if impossible.

graph = [
  [0, 100, 100, 1],
  [0,   0, 100, 0],
  [0,   1,   0, 0],
  [0,  20,   1, 0]
]

Answer: 3 (path: 0321)
Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro