Skip to content

Commit f54db45

Browse files
committed
Add Readme for DFS
1 parent 186509d commit f54db45

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

L-A/0003 DFSGRaph/README.md

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# 0003 DFSGraph ( L-A )
2+
3+
## Problem
4+
5+
Implement a JavaScript function that implements a depth-first search (DFS) algorithm to traverse a graph.
6+
7+
## Test Case
8+
9+
```javascript
10+
graph_edges = [
11+
[1, 2],
12+
[1, 3],
13+
[2, 3],
14+
[3, 4],
15+
[2, 4],
16+
[4, 6],
17+
[5, 6],
18+
[1, 6],
19+
];
20+
```
21+
22+
## Solution
23+
24+
```javascript
25+
const DFSGraphTraversal = (graph, start, visited = new Set()) => {
26+
console.log(start);
27+
visited.add(start);
28+
for (let child = 0; child < graph[start].length; child++) {
29+
if (visited.has(graph[start][child]) === false) {
30+
DFSGraphTraversal(graph, graph[start][child], visited);
31+
}
32+
}
33+
};
34+
```
35+
36+
## How it works
37+
38+
- We first create the graph out of the given array of edges using an `Object`.
39+
- We then run the `DFSGraphTraversal` function to execute the depth first search.
40+
- In the function, we have three parameters; namely the `graph`, the `start` node and the `visited` set which is empty by default.
41+
- Firstly, we print the `start` node and then we add the node to the `visited` set.
42+
- We then run a for loop for the elements present in the `graph[start]` array.
43+
- If the current element is not present in the `visited` set, then recursively call the `DFSGraphTraversal` function with the same `graph` and `visited` set, but with the current element as the `start` node.
44+
- This function will run until all the nodes are visited in the `graph`.
45+
46+
## References
47+
48+
- [Youtube](https://youtu.be/IG1ABs6lVMw)
49+
50+
## Problem Added By
51+
52+
- [khairalanam](https://github.com/khairalanam)
53+
54+
## Contributing
55+
56+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
57+
58+
Please make sure to update tests as appropriate.

0 commit comments

Comments
 (0)