Skip to main content
LeetCode 847, Hard. Topics: Dynamic Programming, Bit Manipulation, Breadth-First Search, Graph Theory, Bitmask. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 17 parametrized pytest cases, and a playground notebook:

Problem

You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge. Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

Examples

Example 1
Example 2

Constraints

  • n == graph.length
  • 1 <= n <= 12
  • 0 <= graph[i].length < n
  • graph[i] does not contain i.
  • If graph[a] contains b, then graph[b] contains a.
  • The input graph is always connected.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026