-
깊이 우선 탐색 (Depth-First Search)Algorithms & Data Structure 2021. 8. 20. 21:56
깊이 우선 탐색이란
- 그래프 탐색 알고리즘
- 노드의 자식들을 먼저 탐색하는 알고리즘
- 오른쪽 노드 먼저, 왼쪽 노드 먼저는 상관 없다.
구현하기
graph = dict() graph['A'] = ['B', 'C'] graph['B'] = ['A', 'D'] graph['C'] = ['A', 'G', 'H', 'I'] graph['D'] = ['B', 'E', 'F'] graph['E'] = ['D'] graph['F'] = ['D'] graph['G'] = ['C'] graph['H'] = ['C'] graph['I'] = ['C', 'J'] graph['J'] = ['I']
def dfs(graph, start_node): visited, need_visit = list(), list() need_visit.append(start_node) while need_visit: node = need_visit.pop() if node not in visited: visited.append(node) need_visit.extend(graph[node]) return visited
dfs(graph, 'A')
Out[8]:
['A', 'C', 'I', 'J', 'H', 'G', 'B', 'D', 'F', 'E']
Resource: 패캠 알고리즘 올인원 GitHub - DAWUNHAN/Algorithms-and-DataStructure: Algorithms and DataStructure with Python
Algorithms and DataStructure with Python. Contribute to DAWUNHAN/Algorithms-and-DataStructure development by creating an account on GitHub.
github.com
'Algorithms & Data Structure' 카테고리의 다른 글
[자료구조] 스택 (Stack) (0) 2022.01.13 [알고리즘] 탐욕 알고리즘 (Greedy Algorithm) (0) 2021.08.22 [알고리즘] 너비 우선 탐색 (BFS) (0) 2021.08.20 [알고리즘] 순차 탐색 (Sequential Search) (0) 2021.08.18 [알고리즘] 이진 탐색(Binary Search) (0) 2021.08.18