HardNo. 0847
Shortest Path Visiting All Nodes — LeetCode 847 Python Solution
- Pattern
- Bit Manipulation
- Topics
- Bit Manipulation, Breadth-First Search, Graph, Dynamic Programming, Bitmask
- 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
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 1494 | Parallel Courses II | Hard |
| 0329 | Longest Increasing Path in a Matrix | Hard |
| 0464 | Can I Win | Medium |
| 0473 | Matchsticks to Square | Medium |
| 0526 | Beautiful Arrangement | Medium |
| 0638 | Shopping Offers | Medium |
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.