[ํ์ด์ฌ/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
'๐์๊ณ ๋ฆฌ์ฆ > ๐ ๊ฐ๋ ์ ๋ฆฌ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ์ด์ฌ/python] ํ (heap) (0) | 2021.09.06 |
---|---|
[ํ์ด์ฌ/python] ๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ (Dijkstra Algorithm) (0) | 2021.09.02 |
[ํ์ด์ฌ/python] ์งํฉ (0) | 2021.04.05 |
[ํ์ด์ฌ/python] DFS์ BFS (0) | 2021.04.05 |
[์๊ณ ๋ฆฌ์ฆ] ๋ธ๋ฃจํธํฌ์ค ์๊ณ ๋ฆฌ์ฆ (Brute Force) (0) | 2021.04.02 |