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