Skip to content

Commit e8789b2

Browse files
Merge pull request akshitagit#113 from SamuelSimoes31/master
add dfs algorithm
2 parents 6435a35 + 3f3bc8e commit e8789b2

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Graphs/dfs.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const graph = [
2+
[0,1,0,1],
3+
[1,0,1,1],
4+
[0,1,0,1],
5+
[1,1,1,0]
6+
]
7+
8+
const visited = new Array(graph.length).fill(false);
9+
const stack = [];
10+
11+
const dfs = (node) => {
12+
stack.push(node);
13+
while (stack.length > 0) {
14+
node = stack.pop();
15+
if (visited[node] === false) {
16+
visited[node] = true;
17+
console.log(`visited node ${node}`)
18+
for (let j = 0; j < graph[node].length; j++) {
19+
if (graph[node][j] === 1){
20+
stack.push(j);
21+
}
22+
}
23+
}
24+
}
25+
}
26+
27+
dfs(2);

0 commit comments

Comments
 (0)