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
๋ณต์ฌ