Cod sursa(job #3246633)

Utilizator antonio.grGrigorascu Andrei Antonio antonio.gr Data 3 octombrie 2024 20:16:10
Problema Parcurgere DFS - componente conexe Scor 0
Compilator py Status done
Runda Arhiva educationala Marime 0.97 kb
file2 = open("dfs.out", "w")
def citire():
    file1 = open("dfs.in", "r")

    graph = {}

    line = file1.readline().split()
    n, m = int(line[0]), int(line[1])
    for line in file1.readlines():
        line = line.split()
        x, y = int(line[0]), int(line[1])

        if x not in graph:
            graph[x] = []
        if y not in graph:
            graph[y] = []
        graph[x].append(y)
        graph[y].append(x)

    file1.close()

    return m, n, graph


m, n, graph = citire()
visited = set()
count = 0

def dfs(graph, source, prev, visited):
    if source in visited:
        return
    visited.add(source)
    global count

    count += 1

    for v in graph[source]:
        if v == prev:
            continue
        if v not in visited:
            dfs(graph, v, source, visited)


def main():
    dfs(graph, 1, -1, visited)

    file2.write(str(count))
    file2.close()


if __name__ == "__main__":
    main()