[ํŒŒ์ด์ฌ/python] DFS, BFS ๊ตฌํ˜„ (์žฌ๊ท€)

2021. 7. 3. 12:18

DFS

def dfs(graph, v, visited):
	#ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
    visited[v] = True
    print(v, end=' ')
    # ํ˜„์žฌ ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ๋œ ๋‹ค๋ฅธ ๋…ธ๋“œ๋ฅผ ์žฌ๊ท€์ ์œผ๋กœ ๋ฐฉ๋ฌธ
    for i in graph[v]:
    	if not visitied[i]:
        	dfs(graph, i, visited)
            

graph = [
	[],
    [2, 3],
    [1],
    [1, 4],
    [3]
  ]

# ๊ฐ ๋…ธ๋“œ๊ฐ€ ๋ฐฉ๋ฌธ๋œ ์ •๋ณด๋ฅผ ํ‘œํ˜„
visited = [False] * 9

# ์ •์˜๋œ DFS ํ•จ์ˆ˜ ํ˜ธ์ถœ
dfs(graph, 1, visitied)
   

 

BFS

from collections import deque

def bfs(graph, start, visited):
	# ํ ๊ตฌํ˜„์„ ์œ„ํ•ด deque ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์‚ฌ์šฉ
    queue = deque([start])
    # ํ˜„์žฌ ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ
    visited[start] = True
    # ํ๊ฐ€ ๋นŒ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
    while queue:
    	# ํ์—์„œ ํ•˜๋‚˜์˜ ์›์†Œ๋ฅผ ๋ฝ‘์•„ ์ถœ๋ ฅํ•˜๊ธฐ
        v = queue.popleft()
        print(v, end = ' ')
        # ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ธ์ ‘ํ•œ ์›์†Œ๋“ค์„ ํ์— ์‚ฝ์ž…
        for i in graph[v]:
        	if not visited[i]:
            	queue.append(i)
                visited[i] = True
                
                

graph = [
	[],
    [2, 3],
    [1],
    [1, 4],
    [3]
   ]

visited = [False] * 5

bfs(graph, 1, visited)
728x90

BELATED ARTICLES

more