Pagini recente » Cod sursa (job #96090) | Cod sursa (job #2721853) | Cod sursa (job #3201871) | Cod sursa (job #2809025) | Cod sursa (job #2922130)
import queue
from urllib import response
def read_graph():
with open('bfs.in') as f:
lines = f.readlines()
N, M, S = lines[0].split(' ')
M = int(M)
N = int(N) + 1
S = int(S)
matrix = [[] for _ in range(N)]
for i in range(1, len(lines)):
x, y = lines[i].split(' ')
x = int(x)
y = int(y)
matrix[x].append(y)
return matrix, N, S
def bfs(matrix, n, s):
costs = [-1] * n
costs[s] = 0
print(costs)
queue = [s]
while len(queue) != 0:
el = queue.pop(0)
for nod in matrix[el]:
if costs[nod] == -1:
costs[nod] = costs[el] + 1
queue.append(nod)
return costs
def write_response(resp):
with open('bfs.out', 'w') as f:
f.write(resp)
if __name__ == "__main__":
matrix, N, S = read_graph()
costs = bfs(matrix, N, S)
resp = " ".join([str(x) for x in costs[1:]])
write_response(resp)