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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

2606๋ฒˆ: ๋ฐ”์ด๋Ÿฌ์Šค

์ฒซ์งธ ์ค„์—๋Š” ์ปดํ“จํ„ฐ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์ปดํ“จํ„ฐ์˜ ์ˆ˜๋Š” 100 ์ดํ•˜์ด๊ณ  ๊ฐ ์ปดํ“จํ„ฐ์—๋Š” 1๋ฒˆ ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ๋ฒˆํ˜ธ๊ฐ€ ๋งค๊ฒจ์ง„๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” ๋„คํŠธ์›Œํฌ ์ƒ์—์„œ ์ง์ ‘ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ์ปดํ“จํ„ฐ ์Œ์˜ ์ˆ˜๊ฐ€ ์ฃผ์–ด๏ฟฝ๏ฟฝ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์›œ ๋ฐ”์ด๋Ÿฌ์Šค๊ฐ€ ํ•˜๋‚˜์˜ ๋„คํŠธ์›Œํฌ ์˜์—ญ์—์„œ ํผ์ง„๋‹ค. 1๋ฒˆ ์ปดํ“จํ„ฐ๋ถ€ํ„ฐ ์‹œ์ž‘ํ•˜์—ฌ ์›œ ๋ฐ”์ด๋Ÿฌ์Šค๊ฐ€ ๊ฐ์—ผ๋˜๋Š” ์ปดํ“จํ„ฐ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋ฌธ์ œ๋Š” BFS/DFS ํƒ์ƒ‰์„ ํ†ตํ•ด 1๋ฒˆ ๋…ธ๋“œ๋กœ๋ถ€ํ„ฐ ํƒ์ƒ‰ ๊ฐ€๋Šฅํ•œ ์˜์—ญ์„ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ดˆ๊ธฐ์— ์ž…๋ ฅ๋˜๋Š” ๊ทธ๋ž˜ํ”„์˜ ์ •๋ณด๋ฅผ ์–‘๋ฐฉํ–ฅ์œผ๋กœ ๊ธฐ๋กํ•˜๊ณ  ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•˜๋ฉด ๋œ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin
from collections import defaultdict, deque


def bfs(start):
    q = deque([start])

    while q:
        cur_node = q.popleft()

        for next_node in graph[cur_node]:
            if next_node not in visited:
                visited.append(next_node)
                q.append(next_node)

    # 1๋ฒˆ ์ปดํ“จํ„ฐ๋ฅผ ์ œ์™ธํ•œ ๋‹ค๋ฅธ ๋…ธ๋“œ๋“ค.
    return len(visited) - 1


if __name__ == '__main__':
    n = int(stdin.readline())
    graph = defaultdict(set)
    visited = [1]

    for _ in range(int(stdin.readline())):
        node1, node2 = map(int, stdin.readline().split())
        graph[node1].add(node2)
        graph[node2].add(node1)

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