Search

DFS/BFS

Created At
2022/02/04 18:11
Updated At
2023/04/06 09:29
๋ถ„๋ฅ˜
์•Œ๊ณ ๋ฆฌ์ฆ˜

DFS

์žฌ๊ท€ ์‚ฌ์šฉ

# ์žฌ๊ท€ ์ด์šฉ def dfs(v): print(v, end=" ") # ํ˜„์žฌ ๋…ธ๋“œ์™€ ์ธ์ ‘ํ•œ ๋…ธ๋“œ๋“ค ์ฒดํฌ for i in graph[v]: # ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ ์ผ๋•Œ๋งŒ dfs์žฌ๊ท€ if visited[i] == 0: visited[i] = 1 # ๋…ธ๋“œ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ dfs(i) graph = [ [], [2, 3, 8], [1, 7], [1, 4, 5], [3, 5], [3, 4], [7], [2, 6, 8], [1, 7] ] visited = [0] * 9 visited[1] = 1 dfs(1) # 1 2 7 6 8 3 4 5
Python
๋ณต์‚ฌ

์Šคํƒ ์‚ฌ์šฉ

# ์Šคํƒ ์ด์šฉ def dfs(v): stack = [v] # ํ˜„์žฌ ๋…ธ๋“œ ์Šคํƒ์— ์ถ”๊ฐ€ while stack: cur = stack.pop() if visited[cur] == 0: # ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๋…ธ๋“œ์ผ ๋•Œ visited[cur] = 1 # ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ print(cur, end=" ") # ์ธ์ ‘๋…ธ๋“œ๋“ค ๋’ค์ง‘์–ด์„œ extend (์ž‘์€๋…ธ๋“œ๋“ค๋ถ€ํ„ฐ ๋จผ์ € ๋ฐฉ๋ฌธํ•˜๊ธฐ ์œ„ํ•ด) stack.extend(graph[cur][::-1]) graph = [ [], [2, 3, 8], [1, 7], [1, 4, 5], [3, 5], [3, 4], [7], [2, 6, 8], [1, 7] ] visited = [0] * 9 dfs(1) # 1 2 7 6 8 3 4 5
Python
๋ณต์‚ฌ

BFS

from collections import deque def bfs(start): q = deque([start]) # ์‹œ์ž‘๋…ธ๋“œ ํ์— ๋„ฃ๊ณ  ์‹œ์ž‘ visited[start] = 1 # ์‹œ์ž‘๋…ธ๋“œ ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ # bfs ๋ฉ”์ธ๋กœ์ง while q: v = q.popleft() # ํ์—์„œ ๋…ธ๋“œ ํ•˜๋‚˜ pop(์‹ค์ œ ๋ฐฉ๋ฌธ) print(v, end=" ") for node in graph[v]: # popํ•œ ๋…ธ๋“œ์™€ ์ธ์ ‘ํ•œ ๋…ธ๋“œ๋“ค ์ฒดํฌ if visited[node] == 0: # ์ธ์ ‘๋…ธ๋“œ๊ฐ€ ๋ฏธ๋ฐฉ๋ฌธ๋…ธ๋“œ์ผ ๋•Œ๋งŒ visited[node] = 1 # ๋ฐฉ๋ฌธ์ฒ˜๋ฆฌ q.append(node) # ํ์— ์ถ”๊ฐ€ graph = [ [], [2, 3, 8], [1, 7], [1, 4, 5], [3, 5], [3, 4], [7], [2, 6, 8], [1, 7] ] visited = [0] * 9 bfs(1) # 1 2 3 8 7 4 5 6
Python
๋ณต์‚ฌ

๋ ˆํผ๋Ÿฐ์Šค

class myGraph: def __init__(self): self.graph = {} def addInfo(self, startV, endVs): self.graph[startV] = endVs def addEdge(self, startV, endV): self.graph[startV].append(endV) def addVertex(self, V): self.graph[V] = [] def bfs(self, startV): q = [startV] visited = [startV] while q: # ์ž๋ฃŒ์–‘์ด ์ปค์ง€๋ฉด deque.popleft()๋ฅผ ์“ฐ๋Š”๊ฒŒ ์‹œ๊ฐ„์ด ๋น ๋ฅด๋‹ค. nowV = q.pop(0) for nextV in self.graph[nowV]: if nextV not in visited: q.append(nextV) visited.append(nextV) return visited def dfs(self, startV): s = [startV] visited = [] while s: nowV = s.pop() if nowV not in visited: visited.append(nowV) s.extend(self.graph[nowV][::-1]) return visited def dfs_recursive(self, startV, visited=[]): visited.append(startV) for nextV in self.graph[startV]: if nextV not in visited: self.dfs_recursive(nextV, visited) return visited g = myGraph() g.addInfo( 'A', ['B', 'E', 'I']) g.addInfo( 'B', ['A', 'C']) g.addInfo( 'C', ['B', 'D']) g.addInfo( 'D', ['C']) g.addInfo( 'E', ['A', 'F', 'H']) g.addInfo( 'F', ['E', 'G']) g.addInfo( 'G', ['F']) g.addInfo( 'H', ['E']) g.addInfo( 'I', ['A', 'J']) g.addInfo( 'J', ['I']) print(g.bfs('A')) print(g.dfs('A')) print(g.dfs_recursive('A')) # ['A', 'B', 'E', 'I', 'C', 'F', 'H', 'J', 'D', 'G'] # ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] # ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
Python
๋ณต์‚ฌ