-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs-example.py
More file actions
34 lines (27 loc) ยท 791 Bytes
/
dfs-example.py
File metadata and controls
34 lines (27 loc) ยท 791 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# DFS ๋ฉ์๋ ์ ์
def dfs(graph, v, visited):
# ํ์ฌ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
visited[v] = True
print(v, end=" ")
# ํ์ฌ ๋
ธ๋์ ์ฐ๊ฒฐ๋ ๋ค๋ฅธ ๋
ธ๋๋ฅด ์ฌ๊ท์ ์ผ๋ก ๋ฐฉ๋ฌธ
for i in graph[v]:
if not visited[i]:
print(visited)
dfs(graph, i, visited)
# ๊ฐ ๋
ธ๋๊ฐ ์ฐ๊ฒฐ๋ ์ ๋ณด๋ฅผ ํํ (2์ฐจ์ ๋ฆฌ์คํธ)
graph = [
[], # ๋
ธ๋์ ๋ฒํธ๊ฐ 1๋ฒ์ธ ๊ฒฝ์ฐ ์ธ๋ฑ์ค 0์ ๋น์๋๊ณ 1๋ถํฐ ์์ํ๊ธฐ ์ํจ
[2, 3, 8],
[1, 7],
[1, 4, 5],
[3, 5],
[3, 4],
[7],
[2, 6, 8],
[1, 7]
]
# ๊ฐ ๋
ธ๋๊ฐ ๋ฐฉ๋ฌธ๋ ์ ๋ณด๋ฅผ ํํ (1์ฐจ์ ๋ฆฌ์คํธ)
visited = [False] * 9 # ๋
ธ๋ 8 ๊ฐ + 0๋ฒ ์ธ๋ฑ์ค
# ์ ์๋ DFS ํจ์ ํธ์ถ
dfs(graph, 1, visited)
# 1 2 7 6 8 3 4 5