-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.py
68 lines (51 loc) · 1.47 KB
/
bfs.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'bfs' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER m
# 3. 2D_INTEGER_ARRAY edges
# 4. INTEGER s
#
def bfs(n, m, edges, s):
# Write your code here
store = {}
for edge in edges:
if edge[0] in store:
store[edge[0]] = store[edge[0]] + [edge[0]]
else:
store[edge[0]] = [edge[1]]
fringe = [s]
distances = [-1 for node in range(n)]
count = 1
while fringe:
cur = fringe.pop(0)
neighbors = store[cur]
for neighbor in neighbors:
if not neighbor:
distances[neighbor]= count
for n in store[neighbor]:
if not distances[neighbor]:
fringe.append(neighbor)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
q = int(input().strip())
for q_itr in range(q):
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
m = int(first_multiple_input[1])
edges = []
for _ in range(m):
edges.append(list(map(int, input().rstrip().split())))
s = int(input().strip())
result = bfs(n, m, edges, s)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()