Cod sursa(job #2922129)

Utilizator ElenaaaColominschi Elena Elenaaa Data 4 septembrie 2022 15:11:39
Problema BFS - Parcurgere in latime Scor 0
Compilator py Status done
Runda Arhiva educationala Marime 1 kb
import queue
from urllib import response


def read_graph():
    with open('D:\\Algo\\Amazon\\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('D:\\Algo\\Amazon\\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)