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

Programming/๋ฐฑ์ค€

230219 [2606: DFS]

ํ•ด๋“œ์œ„๊ทธ 2023. 9. 2. 17:01

- 2606

 

์ „์—ญ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ cnt๊ฐ’์„ ์ฒดํฌํ•˜๋Š๋ผ ์• ๋จน์—ˆ๋Š”๋ฐ

๊ตณ์ด ๊ทธ๋Ÿด ํ•„์š”๊ฐ€ ์—†์—ˆ๋‹ค

์–ด์ฐจํ”ผ ๋ฐฉ๋ฌธํ•œ ๊ฐ’์„ visited์— ์ €์žฅํ•˜๊ธฐ ๋•Œ๋ฌธ์—

sum(visited) -1 ํ•ด์ฃผ๋ฉด ๋˜๋Š” ๊ฒƒ!

 

*์ƒ๊ฐ์˜ ์ „ํ™˜ ์ƒ๊ฐ์˜ ๋ฐœ์ƒ!!

 

import sys
from collections import deque

input = sys.stdin.readline

N = int(input().rstrip())
M = int(input().rstrip())

graph = [[0]*(N+1) for i in range(N+1)]
visited = [0]*(N+1)

for i in range(M):
    n1, n2 = map(int, input().rstrip().split())
    graph[n1][n2] = graph[n2][n1] = 1
    
def DFS(V):
    global cnt
    visited[V] = 1
    
    for i in range(1, N+1):
        if visited[i] == 0 and graph[V][i] == 1:
            cnt += 1
            DFS(i)

cnt = 0
DFS(1)
print(cnt)
๋ฐ˜์‘ํ˜•

'Programming > ๋ฐฑ์ค€' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

230228 [1327: ์†ŒํŠธ๊ฒŒ์ž„]  (0) 2023.09.02
230219 [10026: DFS]  (0) 2023.09.02
230219 [1260: DFS&BFS]  (0) 2023.09.02
230207 [1929 : ๋” ๋น ๋ฅด๊ฒŒ ์†Œ์ˆ˜ ๊ตฌํ•˜๊ธฐ]  (0) 2023.09.02
230204 [๊ธฐ๋ณธ์ˆ˜ํ•™ 1]  (0) 2023.09.02