Skip to content

Commit cf8759b

Browse files
committed
Find if Path Exists in Graph / 湲곗�
1 parent f59dde8 commit cf8759b

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
var validPath = function (n, edges, source, destination) {
2+
const adjacencyList = new Array(n).fill(0).map(() => []);
3+
for (const [nodeA, nodeB] of edges) {
4+
adjacencyList[nodeA].push(nodeB);
5+
adjacencyList[nodeB].push(nodeA);
6+
}
7+
8+
const visitedNodes = new Array(n).fill(false);
9+
const bfsQueue = [source];
10+
visitedNodes[source] = true;
11+
12+
while (bfsQueue.length) {
13+
const currentNode = bfsQueue.shift();
14+
if (currentNode === destination) return true;
15+
16+
for (const adjacentNode of adjacencyList[currentNode]) {
17+
if (!visitedNodes[adjacentNode]) {
18+
visitedNodes[adjacentNode] = true;
19+
bfsQueue.push(adjacentNode);
20+
}
21+
}
22+
}
23+
24+
return false;
25+
};

0 commit comments

Comments
 (0)