Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Baekjoon

[๋ฐฑ์ค€] 1260๋ฒˆ - DFS์™€ BFS (ํŒŒ์ด์ฌ)

๊ฐ์ž ๐Ÿฅ” 2021. 10. 14. 15:11
๋ฐ˜์‘ํ˜•

 ๋ฌธ์ œ๋งํฌ

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

 

1260๋ฒˆ: DFS์™€ BFS

์ฒซ์งธ ์ค„์— ์ •์ ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000), ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 10,000), ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•  ์ •์ ์˜ ๋ฒˆํ˜ธ V๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ M๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ„์„ ์ด ์—ฐ๊ฒฐํ•˜๋Š” ๋‘ ์ •์ ์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ์–ด๋–ค ๋‘ ์ •์  ์‚ฌ

www.acmicpc.net

 

๋‚˜์˜ ํ’€์ด

dfs/bfs๋ฅผ ํ™œ์šฉํ•œ ์ฝ”๋“œ๋ฅผ ํ’€์–ด๋ณด์ง€ ์•Š์•„์„œ ์ฐธ๊ณ ์ž๋ฃŒ๋ฅผ ํ™œ์šฉํ•ด ๋ฌธ์ œ๋ฅผ ํ›‘์–ด๋ณด๋Š” ์‹œ๊ฐ„์„ ๊ฐ€์กŒ๋‹ค. ์ง€๊ธˆ์€ ๋‹จ์ˆœํžˆ ๊ทธ๋ž˜ํ”„๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ์ง€๋งŒ, ์•ž์œผ๋กœ๋Š” ์‘์šฉ๋ฌธ์ œ๋ฅผ ๊ณ„์† ํ’€์–ด๋ณด๋ฉด์„œ LG CNS ์ฝ”ํ…Œ ์ „๊นŒ์ง€ bfs, dfs๋ฅผ ์ •๋ณตํ•˜๋Š”๊ฒŒ ๋ชฉํ‘œ๋‹ค. ๊ผญ dfs/bfs๋ฌธ์ œ๋Š” ํ’€๊ณ  ๋‚˜์˜ค๋ฆฌ๋ผ!

bfs, dfs์˜ ์ •๋ง ๊ฐ„๋‹จํ•œ ๊ฐœ๋…) https://didu-story.tistory.com/98?category=902867
๋‚ด๊ฐ€ ์ฐธ๊ณ ํ•œ ์ž๋ฃŒ ) https://itholic.github.io/python-bfs-dfs/

 

[์•Œ๊ณ ๋ฆฌ์ฆ˜] ํƒ์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜ DFS, BFS

-- ๋ณธ ํฌ์ŠคํŒ…์€ ์ด๊ฒƒ์ด ์ทจ์—…์„ ์œ„ํ•œ ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ๋‹ค with ํŒŒ์ด์ฌ ์ฑ…์„ ์ฐธ๊ณ ํ•˜์—ฌ ์ž‘์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. 1. DFS Depth First Search, ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ ๊ทธ๋ž˜ํ”„์˜ ๊นŠ์€ ๋ถ€๋ถ„์„ ์šฐ์„ ์ ์œผ๋กœ ํƒ์ƒ‰ํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ฃผ๋กœ ์Šค

didu-story.tistory.com

 

from collections import deque

N,M,V=map(int,input().split())
matrix=[[0]*(N+1) for i in range(N+1)]

for i in range(M):
    a, b = map(int, input().split())
    matrix[a][b] = matrix[b][a] = 1
    
visited = [0] * (N+1)
############์ž…๋ ฅ ํ˜•์‹ ์™ธ์šฐ๊ธฐ############

def dfs(v):
		#์‹œ์ž‘๋…ธ๋“œ๋Š” ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ ๋ถ€ํ„ฐ ํ•˜๊ณ  ์‹œ์ž‘
    visited[v] = 1
    print(v, end=' ')
    for i in range(1, N+1):
				# matrix[v][i] ๋ฅผ ์“ฐ๋Š” ์ด์œ ๋Š” ์ธ์ ‘ํ–‰๋ ฌ ์ค‘, visited=0์ธ๊ฑฐ ์ฐพ๋Š”๊ฑฐ์ž„
				# ๋งŒ์•ฝ ์ธ์ ‘ํ–‰๋ ฌ์ด ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ๋ผ๋ฉด, ๋ฐฉ๋ฌธํ•ด์„œ dfs์žฌ๊ท€๋กœ ๋Œ๋ ค์ฃผ๊ธฐ
        if (visited[i]==0 and matrix[v][i]==1):
            dfs(i)

def bfs(v):
    queue = deque([v])
    #๋ฌธ์ œ๊ฐ€ dfs๋จผ์ € ๋Œ๋ฆฌ๊ณ  bfs๋Œ๋ฆฌ๋Š” ๊ฒƒ
		#๋”ฐ๋ผ์„œ dfs๋Œ์•„๊ฐ€๋ฉด์„œ ๋ฐฉ๋ฌธ๋…ธ๋“œ๋ฅผ 1๋กœ ๋ฐ”๊พธ์—ˆ์œผ๋‹ˆ๊นŒ ์—ฌ๊ธฐ์„  0์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ๋ฉด์„œ ๋ฐฉ๋ฌธ
    visited[v] = 0
    
		#๋ฐฉ๋ฌธํ•  ๋…ธ๋“œ๋ฅผ queue์— ๋„ฃ์–ด์ฃผ๊ณ  ์ด๋™ํ• ๊ฑด๋ฐ ์—ฌ๊ธฐ queue์— ์•„๋ฌด๊ฒƒ๋„ ์—†์„๋–„๊นŒ์ง€ ์ง„ํ–‰
		#์‹œ์ž‘๋…ธ๋“œv๋ฅผ queue์— ๋„ฃ๊ณ  ์‹œ์ž‘
    while queue:
        v = queue.popleft()
        print(v, end=' ')
        for i in range(1, N+1):
						#visited๊ฐ€ ์•„์ง 1์ด๊ณ , ์ธ์ ‘ํ–‰๋ ฌ์ด ์žˆ๋‹ค๋ฉด ๋ฐฉ๋ฌธํ•ด์ค˜์•ผํ•˜๋‹ˆ๊นŒ queue์— ๋„ฃ๊ณ  ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌํ•ด์คŒ
            if (visited[i]==1 and matrix[v][i]==1):
                queue.append(i)
                visited[i] = 0
                
dfs(V)
print()
bfs(V)
๋ฐ˜์‘ํ˜•