Search⌘ K
AI Features

Solution: Shortest Path Visiting All Nodes

Explore how to solve the shortest path visiting all nodes problem in an undirected graph. Learn to apply breadth-first search combined with state compression using bitmasks to track visited nodes. Understand why BFS guarantees the shortest path and how revisiting states is avoided to optimize search efficiency.

Statement

You are given an undirected connected graph with n nodes numbered from 00 to n1n-1. The graph is provided as an adjacency list, graph, where graph[i] contains all nodes that share an edge with node i.

Your task is to find the length of the shortest path that visits every node. You may:

  • Start from any node.

  • End at any node.

  • Revisit nodes and reuse edges as many times as needed.

Constraints:

  • n ==== graph.length

  • 11 \leq n 12\leq 12 ...