Skip to content

Commit 8dcfb92

Browse files
committed
Find if Path Exists in Graph / 기초
1 parent 7817495 commit 8dcfb92

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @param {number} source
5+
* @param {number} destination
6+
* @return {boolean}
7+
*/
8+
var validPath = function (n, edges, source, destination) {
9+
const graph = Array.from({ length: n }, () => []);
10+
11+
edges.forEach(([u, v]) => {
12+
graph[u].push(v);
13+
graph[v].push(u);
14+
});
15+
16+
const visited = new Set();
17+
18+
const dfs = (node) => {
19+
if (node === destination) return true;
20+
visited.add(node);
21+
22+
for (const neighbor of graph[node]) {
23+
if (!visited.has(neighbor) && dfs(neighbor)) {
24+
return true;
25+
}
26+
}
27+
28+
return false;
29+
};
30+
31+
return dfs(source);
32+
};

0 commit comments

Comments
 (0)