๊ทธ๋ํ ํ์ ์๊ณ ๋ฆฌ์ฆ
๊ทธ๋ํ ํ์ ์๊ณ ๋ฆฌ์ฆ์๋ ๊น์ด์ฐ์ ํ์(DFS)๊ณผ ๋๋น์ฐ์ ํ์(BFS)์ด ์๋ค.
DFS(Depth First Search, ๊น์ด์ฐ์ ํ์)
๊น์ด ์ฐ์ ํ์์ผ๋ก Stack์ ์ด์ฉํ๋ค. ๋ฃจํธ ๋
ธํธ์์ ์ถ๋ฐํด ํ๋์ ๊ฒฝ๋ก๋ฅผ ๋๊น์ง ํ์ํ ํ ๋ค๋ฅธ ๊ฒฝ๋ก๋ฅผ ํ์ํ๋ค. ๋ ์ด์ ํ์ํ ๋
ธ๋๊ฐ ์๋์ง ๋ฐฉ๋ฌธํ ๋
ธ๋๋ฅผ ๊ฒ์ฌํ๋ฉด์ ํ์ํ๋ค.
print("Graph - DFS")
graph = {
'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A']),
'D': set(['B', 'F']),
'E': set(['B']),
'F': set(['D'])
}
root = 'A'
def DFS(graph, root):
visited = []
stack = [root]
while len(stack) > 0:
node = stack.pop()
if node not in visited:
visited.append(node)
stack += graph.get(node) - set(visited)
return visited
print(DFS(graph, root))
BFS(Breadth First Search, ๋๋น์ฐ์ ํ์)
๋๋น์ฐ์ ํ์์ Queue๋ฅผ ์ด์ฉํ์ฌ ๋ฃจํธ ๋
ธ๋์ ์ธ์ ํ ๋
ธ๋๋ฅผ ์ฐ์ ๋ฐฉ๋ฌธํ๋ค.
print("Graph - BFS")
graph = {
'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A']),
'D': set(['B', 'F']),
'E': set(['B']),
'F': set(['D'])
}
root = 'A'
def BFS(graph, root):
from collections import deque
visited = []
queue = deque([root])
while len(queue) > 0:
node = queue.popleft()
if node not in visited:
visited.append(node)
queue += graph.get(node) - set(visited)
return visited
print(BFS(graph, root))