본문 바로가기

가장 먼 노드 with 파이썬 본문

Algorithms/BFS and DFS

가장 먼 노드 with 파이썬

Louisus 2020. 8. 6. 19:04
728x90
from collections import defaultdict, deque


def bfs(graph, start, distances, visited):
    q = deque([start])
    visited[start] = True

    while q:
        current = q.popleft()
        for adj in graph[current]:
            if not visited[adj]:
                visited[adj] = True
                q.append(adj)
                distances[adj] = distances[current] + 1


def solution(n, edge):
    # 그래프 만들기
    graph = defaultdict(list)
    visited = [False] * (n+1)

    for x, y in edge:
        graph[x].append(y)
        graph[y].append(x)

    # bfs 탐색 (최단 거리 구하기 위함)
    distances = [0]*(n+1)
    bfs(graph, 1, distances, visited)

    return distances.count(max(distances))
Comments