Data Structures: Depth-First Search

This commit is contained in:
Manish 2023-09-16 13:11:25 +10:00
parent be75ed68ed
commit 1d1c0c9964

25
Data Structures/dfs.js Normal file
View File

@ -0,0 +1,25 @@
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/depth-first-search
function dfs(graph, root) {
const n_nodes = graph[0].length;
const reachable = new Set([root]);
const stack = [root];
while (stack.length) {
const node = stack.pop();
for (let i = 0; i < n_nodes; i++) {
if (graph[node][i] > 0 && !reachable.has(i)) {
reachable.add(i);
stack.push(i);
}
}
}
return Array.from(reachable);
}
var exDFSGraph = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0],
];
console.log(dfs(exDFSGraph, 3));