Skip to content

Commit

Permalink
Add depth first search graph algo
Browse files Browse the repository at this point in the history
Signed-off-by: Darko Draskovic <[email protected]>
  • Loading branch information
darkodraskovic committed Sep 10, 2022
1 parent 805793e commit b6778a6
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/algorithms/graph.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
const g_connected = [
[2, 6, 10], // 0
[3, 7, 8, 9], // 1
[0, 3, 6], // 2
[1, 2, 4, 6], // 3
[3, 5], // 4
[4, 11], // 5
[0, 2, 3], // 6
[1, 8], // 7
[7, 1], // 8
[1], // 9
[0], // 10
[5], // 11
]

const g_disconnected = [
[2, 6, 10], // 0
[7, 8, 9], // 1
[0, 3, 6], // 2
[2, 6], // 3
[3, 5], // 4
[4, 11], // 5
[0, 2, 3], // 6
[1, 8], // 7
[7, 1], // 8
[1], // 9
[0], // 10
[5], // 11
]

function _dfs_visit(node, graph, visited) {
visited[node] = true;
graph[node].forEach(neighbor => {
if (!visited[neighbor]) _dfs_visit(neighbor, graph, visited);
});
}

function dfs(graph) {
let count = 0;
let visited = Array(graph.length).fill(false);
for (let i = 0; i < graph.length; i++) {
if (!visited[i]) {
count++;
_dfs_visit(i, graph, visited);
}
}
return count;
}

(function () {
dfs(g_connected);
dfs(g_disconnected);
})()

0 comments on commit b6778a6

Please sign in to comment.