Shortest Path Visiting All Nodes — LeetCode 847 Python Solution
- Problem
- #847
- Pattern
- Bit Manipulation
- Reading time
- 4 min
- Source
- leetcode.com
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
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 += 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(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.