LeetCode 847. Shortest Path Visiting All Nodes
2020/7/19
广度优先搜索.
一个 trick 是可以用二进制数表示访问过的节点, 1 表示访问过, 0 表示未访问过. 比如一共 5 个节点 (0-indexed), 则可以用 11001 表示访问过节点 0, 3, 4. 位运算 1<<n
比 2**n
快得多.
from collections import deque
class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
'''
binary representation
e.g. 11001 for nodes 034 visited and 12 unvisited
'''
goal = (1<<len(graph)) - 1
# (curr_node, visited_nodes, steps)
queue = deque((node, 1<<node, 0) for node in range(len(graph)))
seen = set()
while queue:
curr_node, visited_nodes, steps = queue.popleft()
if visited_nodes == goal:
return steps
for adj_node in graph[curr_node]:
state = (adj_node, visited_nodes | 1<<adj_node, steps+1)
if state not in seen:
seen.add(state)
queue.append(state)
return -1