ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

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

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

programmers.co.kr

 

๋ฌธ์ œ ํ’€์ด

 ๊ฐ ๋…ธ๋“œ์˜ ๊ฐ„์„  ์ •๋ณด๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ, 1๋ฒˆ ๋…ธ๋“œ๋กœ๋ถ€ํ„ฐ ๊ฐ€์žฅ ๋ฉ€๋ฆฌ ๋–จ์–ด์ง„ ๋…ธ๋“œ๋ฅผ ํŒŒ์•…ํ•˜ ํ•œ ํ›„, ์ด์™€ ๊ฐ™์€ ๊ฑฐ๋ฆฌ๋ฅผ ๊ฐ€์ง„ ๋…ธ๋“œ๊ฐ€ ๋ช‡ ๊ฐœ์ธ์ง€ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. BFS๋ฅผ ํ†ตํ•œ ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰์„ ์ดํ•ดํ•˜๊ณ  ์žˆ๋‹ค๋ฉด ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค.

 

  • ๊ทธ๋ž˜ํ”„์˜ ๊ฐ„์„  ์ •๋ณด๋ฅผ ํ•˜๋‚˜์˜ ๋ฆฌ์ŠคํŠธ์— ์ดˆ๊ธฐํ™” ํ•œ๋‹ค.
    • ์˜ˆ๋ฅผ ๋“ค์–ด, 1๋ฒˆ ๋…ธ๋“œ์—์„œ 2๋ฒˆ ๋…ธ๋“œ๊ฐ€ ์ ‘๊ทผ ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด, `graph[1].append[2]`์™€ ๊ฐ™์ด ์ง„ํ–‰ํ•˜๋ฉด ๋œ๋‹ค.
    • ๋ฆฌ์ŠคํŠธ ์ธ๋ฑ์Šค์— ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด node๋“ค์— -1์„ ํ•˜์—ฌ ์ฒ˜๋ฆฌํ•˜์˜€๋‹ค.
    • ๊ทธ๋ž˜ํ”„๋Š” ์–‘๋ฐฉํ–ฅ์ด๋ฏ€๋กœ, `graph[1].append[2`]๋ผ๋ฉด `graph[2].append[1]`๋„ ์ฒ˜๋ฆฌํ•ด ์ฃผ์–ด์•ผ ํ•œ๋‹ค.
  • ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ํ™•์ธํ•˜๋Š” `visited`๋ฅผ ํ™œ์šฉํ•˜์—ฌ, ํ˜„์žฌ ๋…ธ๋“œ์— ๋ฐฉ๋ฌธํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฐ ๊ฑฐ๋ฆฌ๋ฅผ ์ฒดํฌํ•œ๋‹ค.
  • BFS๋ฅผ ํ†ตํ•ด, 1๋ฒˆ ๋…ธ๋“œ๋ฅผ ์‹œ์ž‘์œผ๋กœ ํ•˜์—ฌ ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅํ•œ ์ง€์ ์„ ํƒ์ƒ‰ํ•œ ํ›„ `vistied`์— ๊ฑฐ๋ฆฌ๋ฅผ ์ฒดํฌํ•œ๋‹ค.

 

์ฝ”๋“œ

from collections import deque


def solution(n, edge):
    graph = [[] for _ in range(n)]

    # ๊ทธ๋ž˜ํ”„ ์—ฐ๊ฒฐ ์ •๋ณด ์ดˆ๊ธฐํ™”.
    for node, connect in edge:
        graph[node - 1].append(connect - 1)
        graph[connect - 1].append(node - 1)

    # visited๋กœ ๋…ธ๋“œ ๊ฐ„์˜ ๊ธธ์ด๋ฅผ ์นด์šดํŠธ.
    visited = [0] + [-1] * (n - 1)
    # ์ฒซ ๋ฒˆ์งธ ์‹œ์ž‘ ๋…ธ๋“œ๋Š” [1๋ฒˆ ๋…ธ๋“œ]
    q = deque([[0, 0]])

    while q:
        cur_node, dist = q.popleft()

        for next_node in graph[cur_node]:
            if visited[next_node] == -1:
                q.append([next_node, dist + 1])
                visited[next_node] = dist + 1

    # visited์˜ max๊ฐ’๊ณผ ๊ทธ๊ฒƒ์„ ์นด์šดํŠธ ํ•œ๊ฒƒ์€ ๊ฐ€์žฅ ๋จผ ๋…ธ๋“œ์˜ ์ˆ˜.
    return visited.count(max(visited))

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€