File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -186,5 +186,57 @@ for i in 0..<4 {
186186
187187> 이런 표현이 문제에 있다면 → 그래프 탐색 (DFS/BFS) 문제일 가능성 높음!
188188
189+ ---
189190
191+ ## 🔧 DFS & BFS 기본 Swift 템플릿
190192
193+ ### DFS - 재귀 방식
194+
195+ ``` swift
196+ func dfs (_ graph : [[Int ]], _ v : Int , _ visited : inout [Bool ]) {
197+ visited[v] = true
198+ print (v, terminator : " " )
199+
200+ for next in graph[v] {
201+ if ! visited[next] {
202+ dfs (graph, next, & visited)
203+ }
204+ }
205+ }
206+ ```
207+
208+ ### BFS - 큐 사용 방식
209+
210+ ``` swift
211+ func bfs (_ graph : [[Int ]], _ start : Int ) {
212+ var visited = Array (repeating : false , count : graph.count )
213+ var queue = [start]
214+ visited[start] = true
215+
216+ while ! queue.isEmpty {
217+ let current = queue.removeFirst ()
218+ print (current, terminator : " " )
219+
220+ for next in graph[current] {
221+ if ! visited[next] {
222+ visited[next] = true
223+ queue.append (next)
224+ }
225+ }
226+ }
227+ }
228+ ```
229+
230+ ---
231+
232+ ## ❓ 언제 DFS를 재귀로 구현할 수 있을까?
233+
234+ 다음과 같은 조건을 만족하면 재귀 DFS로 충분히 구현 가능하다:
235+
236+ - 그래프의 노드 수가 작다 (보통 10⁴ 이하)
237+ - 재귀 깊이가 깊지 않다 (1000 ~ 2000 이하)
238+ - 문제에서 ** '모든 경로를 방문'** , ** '깊이 우선'** 접근이 필요하다
239+ - 함수 호출 비용을 감수해도 되는 상황이다
240+
241+ ⚠️ 재귀 호출이 많을 경우 ** 스택 오버플로우 위험** 이 있기 때문에,
242+ 특히 노드 수가 수만 개를 넘을 경우 반복문 기반의 DFS나 BFS로 전환하는 것이 안전하다.
You can’t perform that action at this time.
0 commit comments