[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค-Lv3] ๊ฐ€์žฅ ๋จผ ๋…ธ๋“œ / Python

๐Ÿ“š Problem Solving/Programmers

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ฐ€์žฅ ๋จผ ๋…ธ๋“œ

6 [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]] 3

programmers.co.kr

import sys
from collections import deque

input = sys.stdin.readline

n = int(input())
vertex = [list(map(int, input().split())) for _ in range(int(input()))]


def getDistance(start, graph, distance):
    queue = deque()
    queue.append(start)
    while queue:
        x = queue.popleft()
        for i in graph[x]:
            if i == 1:
                continue
            if distance[i] == 0:
                distance[i] += distance[x] + 1
                queue.append(i)
    return distance


def solution(n, vertex):
    graph = [[] for _ in range(n + 1)]
    distance = [0] * (n + 1)

    for a, b in vertex:
        graph[a].append(b)
        graph[b].append(a)

    temp = getDistance(1, graph, distance)

    return temp.count(max(temp))


print(solution(n, vertex))

 

ํ•ด์„ค

์–ด๋ ต์ง€ ์•Š๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋˜ ๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ์˜€๋‹ค.๐Ÿ˜

๊ฐ ์ •์  ๋ณ„๋กœ ๊ฑฐ๋ฆฌ 1๋กœ ์ด์–ด์ง€๋Š” ์ •์ ๋“ค์„ ์ €์žฅํ•œ๋‹ค.

์‹œ์ž‘ ์ •์  1์„ deque์— ์ €์žฅํ•œ๋‹ค. while๋ฌธ ์•ˆ์—์„œ ํ•ด๋‹น ์ •์ ์„ deque์—์„œ ๋นผ๋‚ด๊ณ  ๊ทธ ์ •์ ์œผ๋กœ๋ถ€ํ„ฐ ์ด์–ด์ง„ ์ •์ ๋“ค๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค. ์ด ๋•Œ, ํƒ์ƒ‰ํ•˜์ง€ ์•Š์€ ์ •์ ๋“ค๋งŒ ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ๊ฒƒ์ด ์ค‘์š”!! ๊ฑฐ๋ฆฌ ๊ณ„์‚ฐ์ด ์™„๋ฃŒ๋œ ์ •์ ์€ deque์— ์ €์žฅํ•˜๊ณ  ์ด๋ฅผ ๋ฐ˜๋ณตํ•œ๋‹ค.