-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgraph
More file actions
73 lines (60 loc) · 1.16 KB
/
graph
File metadata and controls
73 lines (60 loc) · 1.16 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from collections import defaultdict
class Graph:
def __init__(self,V):
self.V = V
self.adj = [[] for i in range(V)]
def addEdge(self,v, w):
self.adj[v].append(w)
def DFS(self,s, goal):
visited = [False for i in range(self.V)]
stack = []
stack.append(s)
while(len(stack)):
s = stack[-1]
stack.pop()
if (not visited[s]):
print(s,end=' ')
visited[s] = True
if goal == s:
break
for node in self.adj[s]:
if (not visited[node]):
stack.append(node)
def BFS(self, s, goal):
visited = [False for i in range(self.V)]
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print(s, end = " ")
if goal == s:
break
for i in self.adj[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
#Main
g = Graph(10);
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(0, 3)
g.addEdge(1, 4)
g.addEdge(1, 5)
g.addEdge(2, 6)
g.addEdge(3, 7)
g.addEdge(7, 8)
g.addEdge(7, 9)
""" 0
/ \ \
1 2 3
/ \ | \
4 5 6 7
/ \
8 9
"""
print("Depth First Search:-")
g.DFS(0,9)
print("\n")
print("Breadth First Search")
g.BFS(0,9)