-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepth_First_search.py
More file actions
49 lines (40 loc) · 1.21 KB
/
Depth_First_search.py
File metadata and controls
49 lines (40 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#Time Complexity: O(V+E) where V is number of vertices
# in the graph and E is number of edges in the graph.
#This code is only for undirected graphs
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def DFSUtil(self,v,visited):
visited[v] = True
print(v, end = "") #python3 function
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i,visited)
def DFS(self, v):
visited = [False]*len(self.graph)
self.DFSUtil(v, visited)
'''
def DFS(self):
V = len(self.graph) #total vertices
# Mark all the vertices as not visited
visited =[False]*(V)
# Call the recursive helper function to print
# DFS traversal starting from all vertices one
# by one
for i in range(V):
if visited[i] == False:
self.DFSUtil(i, visited)
'''
g = Graph()
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.DFS(2) #g.DFS()