|
| 1 | +/** |
| 2 | + * 847. Shortest Path Visiting All Nodes |
| 3 | + * https://leetcode.com/problems/shortest-path-visiting-all-nodes/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an |
| 7 | + * array graph where graph[i] is a list of all the nodes connected with node i by an edge. |
| 8 | + * |
| 9 | + * Return the length of the shortest path that visits every node. You may start and stop at any |
| 10 | + * node, you may revisit nodes multiple times, and you may reuse edges. |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * @param {number[][]} graph |
| 15 | + * @return {number} |
| 16 | + */ |
| 17 | +var shortestPathLength = function(graph) { |
| 18 | + const n = graph.length; |
| 19 | + |
| 20 | + if (n === 1) return 0; |
| 21 | + |
| 22 | + const allVisited = (1 << n) - 1; |
| 23 | + const queue = []; |
| 24 | + const visited = new Set(); |
| 25 | + |
| 26 | + for (let i = 0; i < n; i++) { |
| 27 | + const initialState = (1 << i); |
| 28 | + queue.push([i, initialState, 0]); |
| 29 | + visited.add(`${i},${initialState}`); |
| 30 | + } |
| 31 | + |
| 32 | + while (queue.length > 0) { |
| 33 | + const [node, state, distance] = queue.shift(); |
| 34 | + if (state === allVisited) { |
| 35 | + return distance; |
| 36 | + } |
| 37 | + for (const neighbor of graph[node]) { |
| 38 | + const newState = state | (1 << neighbor); |
| 39 | + const key = `${neighbor},${newState}`; |
| 40 | + if (!visited.has(key)) { |
| 41 | + visited.add(key); |
| 42 | + queue.push([neighbor, newState, distance + 1]); |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return -1; |
| 48 | +}; |
0 commit comments