Skip to content

Commit 9793ef2

Browse files
committed
Add DFS Problem
1 parent f54db45 commit 9793ef2

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

L-A/0003 DFSGRaph/DFSGraph.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const DFSGraphTraversal = (graph, start, visited = new Set()) => {
2+
console.log(start);
3+
visited.add(start);
4+
for (let child = 0; child < graph[start].length; child++) {
5+
if (visited.has(graph[start][child]) === false) {
6+
DFSGraphTraversal(graph, graph[start][child], visited);
7+
}
8+
}
9+
};
10+
11+
graph_edges = [
12+
[1, 2],
13+
[1, 3],
14+
[2, 3],
15+
[3, 4],
16+
[2, 4],
17+
[4, 6],
18+
[5, 6],
19+
[1, 6],
20+
];
21+
22+
graph = {};
23+
24+
for (let i = 0; i < graph_edges.length; i++) {
25+
if (graph_edges[i][0] in graph === false) {
26+
graph[graph_edges[i][0]] = [];
27+
graph[graph_edges[i][0]].push(graph_edges[i][1]);
28+
} else {
29+
graph[graph_edges[i][0]].push(graph_edges[i][1]);
30+
}
31+
32+
if (graph_edges[i][1] in graph === false) {
33+
graph[graph_edges[i][1]] = [];
34+
graph[graph_edges[i][1]].push(graph_edges[i][0]);
35+
} else {
36+
graph[graph_edges[i][1]].push(graph_edges[i][0]);
37+
}
38+
}
39+
40+
console.log(graph);
41+
42+
DFSGraphTraversal(graph, 5);

0 commit comments

Comments
 (0)