HardNo. 0847

Shortest Path Visiting All Nodes — LeetCode 847 Python Solution

Topics
Bit Manipulation, Breadth-First Search, Graph, Dynamic Programming, Bitmask
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

PythonSolution
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

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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

Related problems
No.ProblemDifficulty
1494Parallel Courses IIHard
0329Longest Increasing Path in a MatrixHard
0464Can I WinMedium
0473Matchsticks to SquareMedium
0526Beautiful ArrangementMedium
0638Shopping OffersMedium

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.

Free to download. Check it runs on your machine, then pick a plan.