-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path14. BFS.py
More file actions
41 lines (33 loc) · 817 Bytes
/
14. BFS.py
File metadata and controls
41 lines (33 loc) · 817 Bytes
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
# SANYAM MITTAL
# CE 42
# 18001003110
import sys
input = sys.stdin.readline
def multi_input():
return map(int, input().split())
def array_print(arr):
print(' '.join(map(str, arr)))
print("Number of vertices")
V = int(input())
graph = {}
for i in range(1,V+1):
graph[i] = []
print("Total number of edges")
edges = int(input())
print("Node 1 - Node 2")
visited = [0]*(V+1)
for i in range(edges):
n1, n2 = multi_input()
graph[n1].append(n2)
graph[n2].append(n1)
for i in range(1,V+1):
if visited[i]==0:
stack = [i]
visited[i] = 1
while len(stack):
node = stack.pop(0)
print(node, end=' ')
for i in graph[node]:
if visited[node] == 0:
stack.append(i)
visited[node] = 1