-
Notifications
You must be signed in to change notification settings - Fork 0
/
gpt_solution.js
66 lines (51 loc) · 1.66 KB
/
gpt_solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
function validPath(n, edges, source, destination) {
// Step 1: Build adjacency list
let graph = buildGraph(n, edges);
console.log("graph")
console.log(graph)
// Step 2: Initialize BFS
let queue = [];
queue.push(source);
// Step 3: Initialize visited array
let visited = Array(n).fill(false);
// console.log("visited")
// console.log(visited)
visited[source] = true; // this is how the duplicated was prevented.
// Step 4: Perform BFS
while (queue.length > 0) {
let currentVertex = queue.shift();
console.log("currentVertex: " + currentVertex)
// Step 4.1: Check if destination is reached
if (currentVertex === destination) {
console.log(`> Found ${currentVertex} === ${destination}`)
return true;
}
console.log("graph[currentVertex]: " + graph[currentVertex])
// Step 4.2: Iterate through adjacent vertices
for (let neighbor of graph[currentVertex]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.push(neighbor);
}
}
}
// Step 5: No valid path found
return false;
}
function buildGraph(n, edges) {
// const graph = new Array(n).fill(null).map(() => []);
const graph = Array.from({ length: n }, () => []);
// console.log("init")
// console.log(graph)
for (const [u, v] of edges) {
graph[u].push(v);
graph[v].push(u);
}
return graph;
}
// let x = validPath(3, [[0, 1], [1, 2], [2, 0]], 0, 2)
// let x = validPath(6, [[0, 1], [0, 2], [3, 5], [5, 4], [4, 3]], 0, 5)
// let x = validPath(1, [], 0, 0)
let x = validPath(10, [[4, 3], [1, 4], [4, 8], [1, 7], [6, 4], [4, 2], [7, 4], [4, 0], [0, 9], [5, 4]], 5, 9)
console.log("x")
console.log(x)