๋ฐฑ์ค€ & ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/DFS & BFS

[๋ฐฑ์ค€ 2606] [dfs/bfs] ๋ฐ”์ด๋Ÿฌ์Šค

_cactus 2021. 4. 22. 22:09
๋ฐ˜์‘ํ˜•

๐Ÿ’ป ๋ฐฑ์ค€ 2606๋ฒˆ [๋ฐ”์ด๋Ÿฌ์Šค]

 

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

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

www.acmicpc.net

ํ’€์ด)

def dfs(graph, v, visited) : 
    # ๋…ธ๋“œ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
    visited[v] = True
    # ์ธ์ ‘๋…ธ๋“œ ์ˆœํšŒ
    for i in graph[v] :
        if visited[i] == False :
            dfs(graph, i, visited)
            
n_com,n_pair = int(input()),int(input())
input_lst = [list(map(int,input().split())) for _ in range(n_pair)]

graph = [[] for _ in range(n_com+1)]
for e1,e2 in input_lst :
    graph[e1].append(e2)
    graph[e2].append(e1)
visited = [False] * len(graph)
dfs(graph,1,visited)
print(visited.count(True)-1)
๋ฉ”๋ชจ๋ฆฌ ์‹œ๊ฐ„ ์–ธ์–ด ์ฝ”๋“œ๊ธธ์ด
28776KB 76ms Python 3 512B

 

728x90
๋ฐ˜์‘ํ˜•