Skip to content

Commit ed827e8

Browse files
authored
Create 1971-find-if-path-exists-in-graph.js
1 parent f9ceb59 commit ed827e8

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

1971-find-if-path-exists-in-graph.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @param {number} start
5+
* @param {number} end
6+
* @return {boolean}
7+
*/
8+
const validPath = function(n, edges, start, end) {
9+
const graph = {}
10+
for(const [u, v] of edges) {
11+
if(graph[u] == null) graph[u] = new Set()
12+
if(graph[v] == null) graph[v] = new Set()
13+
graph[u].add(v)
14+
graph[v].add(u)
15+
}
16+
const q = [start], visited = new Set()
17+
visited.add(start)
18+
while(q.length) {
19+
const cur = q.shift()
20+
if(cur === end) return true
21+
for(const next of graph[cur]) {
22+
if(visited.has(next)) continue
23+
q.push(next)
24+
visited.add(next)
25+
}
26+
}
27+
28+
return false
29+
};

0 commit comments

Comments
 (0)