๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ๋ฐ”์ด๋Ÿฌ์Šค BOJ #2606

by seolhee2750 2022. 1. 28.
๋ฌธ์ œ

https://www.acmicpc.net/problem/2606

 

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

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

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
n = int(input())
c = int(input())
network = [[] for _ in range(n)]
queue = []
visited = [False] * n
count = 0

for _ in range(c):
    a, b = map(int, input().split())
    network[a-1].append(b-1)
    network[b-1].append(a-1)

def dfs(x):
    if visited[x]: return
    visited[x] = True

    for i in range(len(network[x])):
        dfs(network[x][i])

dfs(0)
for i in visited:
    if i: count += 1
print(count-1)

๐Ÿ‘‰ DFS ๋ฌธ์ œ๋กœ, 2์ฐจ์› ๋ฆฌ์ŠคํŠธ๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ์ปดํ“จํ„ฐ๋งˆ๋‹ค ์—ฐ๊ฒฐ๋œ ์ปดํ“จํ„ฐ๋“ค์„ ํ‘œ์‹œํ•ด์„œ ํƒ์ƒ‰ํ•ด์ฃผ๋Š” ๊ฒƒ์ด ํฌ์ธํŠธ

  • network๋ผ๋Š” ๋น„์–ด์žˆ๋Š” 2์ฐจ์› ๋ฆฌ์ŠคํŠธ๋ฅผ ์ปดํ“จํ„ฐ์˜ ๊ฐœ์ˆ˜ ํฌ๊ธฐ๋กœ ๋งŒ๋“ค์–ด์ฃผ์—ˆ๊ณ ,
    ์ฃผ์–ด์ง„ ๋„คํŠธ์›Œํฌ ์Œ์„ ์ž…๋ ฅ๋ฐ›์œผ๋ฉด์„œ network ๋ฆฌ์ŠคํŠธ์— ์—ฐ๊ฒฐ ํ‘œ์‹œ๋ฅผ ํ•ด์ฃผ์—ˆ๋‹ค.
    EX) 2, 5 ์ž…๋ ฅ -> network[1]์— 4 append, network[4]์— 1 append
  • dfs ํ•จ์ˆ˜์—์„œ ์ฒ˜์Œ์— 0์„ ์ธ์ž๋กœ ๋ฐ›๊ณ , network[0] ์ž๋ฆฌ์— ์ €์žฅ๋œ ๋ฒˆํ˜ธ์˜ ์ปดํ“จํ„ฐ๋“ค์€ ๊ฐ์—ผ๋œ ๊ฒƒ์ด๋ฏ€๋กœ
    for๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ network[0]์— ์ €์žฅ๋œ ์ปดํ“จํ„ฐ๋“ค์— ๋Œ€ํ•œ dfs๋ฅผ ์ง„ํ–‰ํ–ˆ๋‹ค.
    ์ด๋ฏธ ๊ฐ์—ผ๋œ ๊ฒƒ์„ ํ™•์ธํ•œ ์ปดํ“จํ„ฐ๋Š” visited ๋ฆฌ์ŠคํŠธ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ค‘๋ณต์„ ํ”ผํ–ˆ๋‹ค.
  • dfs ํ•จ์ˆ˜๊ฐ€ ์ข…๋ฃŒ๋œ ์ดํ›„์—๋Š” visited ํ•จ์ˆ˜์— True๊ฐ€ ์ €์žฅ๋œ ์ธ๋ฑ์Šค์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ฒฐ๊ณผ๋กœ ์ถœ๋ ฅํ–ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์ผ๋ฐ˜์ ์ธ DFS, BFS ๋ฌธ์ œ์™€๋Š” ์กฐ๊ธˆ ๋‹ค๋ฅธ ์Šคํƒ€์ผ์ด์—ˆ๋˜ ๊ฒƒ ๊ฐ™๊ณ ,
    ๊ทธ๋ž˜์„œ์ธ์ง€ ์‰ฝ์ง€๋งŒ 1์‹œ๊ฐ„ ์ •๋„ ์‹œ๊ฐ„์ด ๊ฑธ๋ ธ๋‹ค.

๋Œ“๊ธ€