> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Shortest Path Visiting All Nodes

> Tested Python solution for LeetCode 847 with 17 pytest cases. Generate a practice environment with lcpy.

LeetCode 847, [Hard](/catalog/hard). Topics: [Dynamic Programming](/catalog/topics/dynamic-programming), [Bit Manipulation](/catalog/topics/bit-manipulation), [Breadth-First Search](/catalog/topics/breadth-first-search), [Graph Theory](/catalog/topics/graph-theory), [Bitmask](/catalog/topics/bitmask). [View on LeetCode](https://leetcode.com/problems/shortest-path-visiting-all-nodes/description/).

Generate this problem as a practice environment: tested reference solution, 17 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 847   # by problem number
lcpy gen -s shortest_path_visiting_all_nodes   # by problem name
```

## 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](https://assets.leetcode.com/uploads/2021/05/12/shortest1-graph.jpg)

```
Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: One possible path is [1,0,2,0,3]
```

![Example 2](https://assets.leetcode.com/uploads/2021/05/12/shortest2-graph.jpg)

```
Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4
Explanation: One possible path is [0,1,4,2,3]
```

### 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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/shortest_path_visiting_all_nodes/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/shortest_path_visiting_all_nodes/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque


class Solution:
    # Time: O(n * 2^n * n) = O(n^2 * 2^n) - each state dequeued once, n edges per state
    # Space: O(n * 2^n) for the visited-state set
    def shortest_path_length(self, graph: list[list[int]]) -> int:
        n = len(graph)
        full = (1 << n) - 1
        queue: deque[tuple[int, int]] = deque((node, 1 << node) for node in range(n))
        seen = {(node, 1 << node) for node in range(n)}
        steps = 0
        while queue:
            for _ in range(len(queue)):
                node, mask = queue.popleft()
                if mask == full:
                    return steps
                for neighbor in graph[node]:
                    state = (neighbor, mask | (1 << neighbor))
                    if state not in seen:
                        seen.add(state)
                        queue.append(state)
            steps += 1
        return steps
```

## Complexity

| Time | Space |
| - | - |
| O(n \* 2^n \* n) = O(n^2 \* 2^n) - each state dequeued once, n edges per state | O(n \* 2^n) for the visited-state set |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.