Shortest Path Visiting All Nodes — LeetCode 847 Python Solution

HardBit ManipulationBreadth-First SearchGraphDynamic ProgrammingBitmask
Problem
#847
Reading time
4 min

The 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.

Example

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

Python solution

Python
class Solution:
    def shortestPathLength(self, graph: List[List[int]]) -> int:
        n = len(graph)
        q = deque()
        vis = set()
        for i in range(n):
            q.append((i, 1 << i))
            vis.add((i, 1 << i))
        ans = 0
        while 1:
            for _ in range(len(q)):
                i, st = q.popleft()
                if st == (1 << n) - 1:
                    return ans
                for j in graph[i]:
                    nst = st | 1 << j
                    if (j, nst) not in vis:
                        vis.add((j, nst))
                        q.append((j, nst))
            ans += 1

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 847. Shortest Path Visiting All Nodes is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 847. Shortest Path Visiting All Nodes?
LeetCode 847. Shortest Path Visiting All Nodes is rated Hard on LeetCode.
What topics does LeetCode 847. Shortest Path Visiting All Nodes cover?
LeetCode 847. Shortest Path Visiting All Nodes is tagged Bit Manipulation, Breadth-First Search, Graph, Dynamic Programming and Bitmask on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview