-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBFSOfGraph.py
47 lines (37 loc) · 1.24 KB
/
BFSOfGraph.py
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
# Problem Description: https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/
from collections import defaultdict
import queue
class Graph():
def __init__(self, vertices):
self.graph = defaultdict(list)
self.V = vertices
def addEdge(self, u, v): # add directed edge from u to v.
self.graph[u].append(v)
def bfs(g, N):
'''
:param g: given adjacency list of graph
:param N: number of nodes in N.
:return: print the bfs of the graph from node 0, newline is given by driver code
'''
q = queue.Queue(maxsize=N)
visited = [False] * N
q.put(0)
visited[0] = True
while(not q.empty()):
node = q.get()
print(node, end=" ")
for i in g[node]:
if(not visited[i]):
q.put(i)
visited[i] = True
if __name__ == '__main__':
test_cases = int(input())
for cases in range(test_cases):
N, E = map(int, input().strip().split())
g = Graph(N)
edges = list(map(int, input().strip().split()))
for i in range(0, len(edges), 2):
u, v = edges[i], edges[i+1]
g.addEdge(u, v) # add a directed edge from u to v
bfs(g.graph, N) # print bfs of graph
print()