LeetCode 0847. Shortest Path Visiting All Nodes Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0847. Shortest Path Visiting All Nodes

Description

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.

Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.

 

Example 1:

Input: graph = [[1,2,3],[0],[0],[0]]
Output: 4
Explanation: One possible path is [1,0,2,0,3]

Example 2:

Input: graph = [[1],[0,2,4],[1,3,4],[2],[1,2]]
Output: 4
Explanation: One possible path is [0,1,4,2,3]

 

Constraints:

  • n == graph.length
  • 1 <= n <= 12
  • 0 <= graph[i].length < n
  • graph[i] does not contain i.
  • If graph[a] contains b, then graph[b] contains a.
  • The input graph is always connected.

Solutions

Solution 1

PythonJavaC++GoTypeScriptRust
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(code-box)

Solution 2

PythonJavaC++
class Solution: def shortestPathLength(self, graph: List[List[int]]) -> int: n = len(graph) def f(state): return sum(((state >> i) & 1) == 0 for i in range(n)) q = [] dist = [[inf] * (1 << n) for _ in range(n)] for i in range(n): heappush(q, (f(1 << i), i, 1 << i)) dist[i][1 << i] = 0 while q: _, u, state = heappop(q) if state == (1 << n) - 1: return dist[u][state] for v in graph[u]: nxt = state | (1 << v) if dist[v][nxt] > dist[u][state] + 1: dist[v][nxt] = dist[u][state] + 1 heappush(q, (dist[v][nxt] + f(nxt), v, nxt)) return 0(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !