Skip to content

Commit 72c7466

Browse files
committed
Depth First Search
1 parent 938d65e commit 72c7466

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

Graphs/dfs.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Using a Python dictionary to act as an adjacency list
2+
graph = {
3+
'5' : ['3','7'],
4+
'3' : ['2', '4'],
5+
'7' : ['8'],
6+
'2' : [],
7+
'4' : ['8'],
8+
'8' : []
9+
}
10+
11+
visited = set() # Set to keep track of visited nodes of graph.
12+
13+
def dfs(visited, graph, node): #function for dfs
14+
if node not in visited:
15+
print (node)
16+
visited.add(node)
17+
for neighbour in graph[node]:
18+
dfs(visited, graph, neighbour)
19+
20+
# Driver Code
21+
dfs(visited, graph, '5')
22+
# 5
23+
# 3
24+
# 2
25+
# 4
26+
# 8
27+
# 7

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,5 @@ Data Structures and Algorithms Patterns implemented in Python.
1717
- [x] [Recursion on Linked List](Recursion/Linked-List)
1818
- [x] [Reverse Linked List](Recursion/Linked-List/Reverse-Linked-List.py)
1919
- [x] [Graphs](Graphs)
20-
- [x] [Breadth First Search](Graphs/bfs.py)
20+
- [x] [Breadth First Search](Graphs/bfs.py)
21+
- [x] [Depth First Search](Graphs/dfs.py)

0 commit comments

Comments
 (0)