#847

Shortest Path Visiting All Nodes

Hard
Dynamic ProgrammingBit ManipulationBreadth-First SearchGraph TheoryBitmaskDynamic ProgrammingBitmaskingGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n^2 * 2^n)
Space
O(n)
O(n * 2^n)
💡

Intuition

Time O(n^2 * 2^n)Space O(n * 2^n)

The optimal approach uses Dynamic Programming with Bitmasking to efficiently track visited nodes and their states. This reduces the number of states we need to explore compared to brute force.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table where dp[mask][i] represents the shortest path to visit nodes represented by 'mask' ending at node 'i'.
  2. 2Step 2: Use BFS to explore all possible paths while updating the DP table based on previously visited nodes.
  3. 3Step 3: Iterate through the DP table to find the minimum path length that visits all nodes.
solution.py16 lines
1from collections import deque
2
3def shortestPathLength(graph):
4    n = len(graph)
5    dp = [[float('inf')] * n for _ in range(1 << n)]
6    for i in range(n):
7        dp[1 << i][i] = 0
8    queue = deque([(mask, i) for i in range(n) for mask in [1 << i]])
9    while queue:
10        mask, u = queue.popleft()
11        for v in graph[u]:
12            new_mask = mask | (1 << v)
13            if dp[new_mask][v] > dp[mask][u] + 1:
14                dp[new_mask][v] = dp[mask][u] + 1
15                queue.append((new_mask, v))
16    return min(dp[(1 << n) - 1][i] for i in range(n))

Complexity note: The time complexity is O(n^2 * 2^n) due to the number of states (2^n) and the processing of each state (up to n neighbors). The space complexity is O(n * 2^n) for storing the DP table.

  • 1Using bitmasking allows us to efficiently track visited nodes.
  • 2Dynamic programming helps to avoid recalculating paths for the same state.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.