Skip to content

Commit 586da8c

Browse files
Merge pull request #208 from Iamtripathisatyam/main
Depth-first Search (DFS) Python
2 parents 3e692a3 + 9fb5e61 commit 586da8c

File tree

4 files changed

+65
-0
lines changed

4 files changed

+65
-0
lines changed

Graphs/DFS/Images/dfs.jpg

16.5 KB
Loading

Graphs/DFS/Images/output.jpg

26.7 KB
Loading

Graphs/DFS/README.md

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
## Overview:
2+
Two techniques are frequently used for graph traversal: These techniques are called **depth-first search (DFS)** and **breadth-first search (BFS)**, although we will just talk about DFS. DFS involves diving deep into the graph and then backtrack when it reaches the bottom.
3+
4+
## What is Depth First Search in Python?
5+
In DFS, *we continue to traverse downwards through linked nodes until we reach the end*, then retrace our steps to check which connected nodes we haven't visited and repeat the process. In depth-first search, we dive deep into the graph and then backtrack when we reach the bottom.
6+
7+
## Algorithm of DFS in Python
8+
Every time we reach a new node, we will take the following steps:
9+
1. We add the node to the top of the stack.
10+
2. Marked it as visited.
11+
3. We check if this node has any adjacent nodes:
12+
1. If it has adjacent nodes, then we ensure that they have not been visited already, and then visited it.
13+
2. We removed it from the stack if it had no adjacent nodes.
14+
15+
## Time & Space Complexity
16+
* **Time Complexity:**
17+
Time complexity of DFS is `O(V+|E|)`, where V is the number of vertices and E is the number of edges.
18+
* **Space Complexity:**
19+
The space complexity of the DFS algorithm is `O(V)`, where V is the number of vertices.
20+
21+
## Input & Output:
22+
<img src="../DFS/Images/dfs.jpg">
23+
24+
### Input:
25+
26+
```python
27+
graph = {
28+
0: [2],
29+
1: [2, 3],
30+
2: [0, 1, 4],
31+
3: [1, 4],
32+
4: [2, 3]
33+
}
34+
```
35+
36+
### Output:
37+
```python
38+
Depth-first search: [0, 2, 1, 3, 4]
39+
```
40+
<img width=50% src="../DFS/Images/output.jpg">

Graphs/DFS/dfs.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def dfs(node, graph, visited, component):
2+
component.append(node) # Store answer
3+
visited[node] = True # Mark visited
4+
5+
# Traverse to each adjacent node of a node
6+
for child in graph[node]:
7+
if not visited[child]: # Check whether the node is visited or not
8+
dfs(child, graph, visited, component)
9+
10+
11+
if __name__ == "__main__":
12+
13+
# Graph of nodes
14+
graph = {
15+
0: [2],
16+
1: [2, 3],
17+
2: [0, 1, 4],
18+
3: [1, 4],
19+
4: [2, 3]
20+
}
21+
node = 0 # Starting node
22+
visited = [False]*len(graph)
23+
component = []
24+
dfs(node, graph, visited, component) # Traverse to each node of a graph
25+
print(f"Following is the Depth-first search: {component}") # Print the answer

0 commit comments

Comments
 (0)