-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbfs dfs.txt
42 lines (35 loc) · 1.15 KB
/
bfs dfs.txt
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
def dfs(visited,graph,node):
if node not in visited:
print(node,end = " ")
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
def bfs(visited, graph, node):
queue = []
visited.add(node)
queue.append(node)
while queue:
s = queue.pop(0)
print(s, end=" ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
def main():
visited1 = set()
visited2 = set()
n = int(input("Enter number of nodes : "))
graph = dict()
for i in range(1,n+1):
edges = int(input("Enter number of edges for node {} : ".format(i)))
graph[i] = list()
for j in range(1,edges+1):
node = int(input("Enter edge {} for node {} : ".format(j,i)))
graph[i].append(node)
print("The following is DFS")
dfs(visited1, graph, 1)
print(" ")
print("The following is BFS")
bfs(visited2, graph, 1)
if __name__=="__main__":
main()