Backtracking
특징
- 주로 재귀호출 사용
- tree traverse, 특히 state tree traverse 문제의 해결방법
- 모든 가능성을 뒤져보는 행위 : 느릴 수 밖에 없음
- 보통 지수함수 이상의 time complexity를 가진다
- 가지치기 (Prunning)을 사용하면 효과의 향상을 가져올 수 있음 (DFS와의 차이)
rough implementation
123456789101112# recursivedef backtracking (candidate):# 01. Reject or acceptanswer = []if isReject(candidate) return []if isAccept(candidate) answer.append(candidate)# 02. Recursive callsubProblem = getFirstChild(candidate)while isValid(subProblem):answer += backtracking(subProblem)subProblem = getNextChild(candidate)return answer
DFS
특징
- recursive / iterative 둘 다 구현 가능
- iterative하게 구현할 경우 stack을 써서 candidate 관리
- Time complexity : O(V + E)
- Space complexity : O(V)
rough implementation ()
1234567891011121314# recursivedef dfs(graph, start, visited=None):# 01. check visit statusif visited == None:visited = set()visited.add(start)# 02. do something with the start vertexdoSomething(start)# 03. recursive callcandidates = [v for v in grpah.getAdj(start) if isVisited(v)]for v in candidates:dfs(graph, v, visited)
BFS
특징
- candiate을 queue로 구현함
- iterative하게 구현해야함 (recursive로는 어려움)
- Time complexity : O(V + E)
- Space complexity : O(V)
rough implementation
123456789101112131415# iterativedef bfs(graph, start):# 01. initializationvisited, queue = set(), [start]while queue != []:# 02. do something with the start vertexdoSomething(start)# 03. find the candidatescandSet = [v in graph.getAdj(start)]for cand in candSet:if isVisited(v) in not visited:queue.append(v)queue.pop(0)
Shortest path finding in graph
- dijkstra algorithm
- Bellman-ford algorithm
- A* search