Skip to content

Commit 603e24c

Browse files
committedMar 20, 2025
Add solution #847
1 parent 3db207a commit 603e24c

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,7 @@
654654
844|[Backspace String Compare](./0844-backspace-string-compare.js)|Easy|
655655
845|[Longest Mountain in Array](./0845-longest-mountain-in-array.js)|Medium|
656656
846|[Hand of Straights](./0846-hand-of-straights.js)|Medium|
657+
847|[Shortest Path Visiting All Nodes](./0847-shortest-path-visiting-all-nodes.js)|Hard|
657658
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
658659
868|[Binary Gap](./0868-binary-gap.js)|Easy|
659660
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

Comments
 (0)
Please sign in to comment.