DFS/BFS
๊ฐ๋
์ ๊ณต๋ถํ๊ณ ๋ฌธ์ ํ๊ธฐ ์์ํ๋ค~!
import sys
def dfs(graph, visit, start_node, N):
print(start_node, end=' ')
stack = []
for i in range(1, N + 1):
if graph[start_node][i]:
graph[start_node][i] = 0
graph[i][start_node] = 0
stack.append(i)
while stack:
node = stack.pop(0)
if node not in visit:
visit.append(node)
dfs(graph, visit, node, N)
def bfs(start_node):
queue = [start_node]
visit = []
while queue:
start_node = queue.pop(0)
visit.append(start_node)
print(start_node, end=' ')
# append step
for i in range(1, N + 1):
if i not in visit and i not in queue:
graph[start_node][i] = 0
graph[i][start_node] = 0
queue.append(i)
print('queue =', queue, 'visit =', visit)
N, M, V = map(int, sys.stdin.readline().rstrip().split())
# Construct Graph
graph = [[0] * (N + 1) for i in range(N + 1)]
visit = []
for i in range(M):
x, y = map(int, sys.stdin.readline().rstrip().split())
graph[x][y] = 1
graph[y][x] = 1
dfs(graph, visit, V, N)
์ด ๋ฌธ์ ์ ๊ฝค ๋ง์ ์๊ฐ์ ์๋ชจํ๋๋ฐ๋ ํ์ง ๋ชปํ๋ค.
์ด์ ์ ์ ๋ฆฌํ DFS/BFS
๊ธ์ ํ์ ๋ฐ์ดํฐ์ ํ์์ด ๋ฌ๋ผ ์ด๋ป๊ฒ ์ ๊ทผํด์ผ ํ๋์ง ๋ชจ๋ฅด๊ฒ ๋ค.
์์ง DFS/BFS
๊ฐ๋
์ด ๋ถ์กฑํด์ ์์ฉ์ด ์๋๋ ๊ฒ ๊ฐ๋ค. ๐ฅ
import sys
def dfs(start_node):
print(start_node, end=' ')
visit[start_node] = 1
for i in range(1, N + 1):
if graph[start_node][i] and visit[i] == 0:
dfs(i)
def bfs(start_node):
queue = [start_node]
visit[start_node] = 0
while queue:
start_node = queue.pop(0)
print(start_node, end=' ')
for i in range(1, N + 1):
if graph[start_node][i] and visit[i] == 1:
queue.append(i)
visit[i] = 0
# input
N, M, V = map(int, sys.stdin.readline().rstrip().split())
# Construct Graph
graph = [[0] * (N + 1) for i in range(N + 1)]
visit = [0 for i in range(N + 1)]
for i in range(M):
x, y = map(int, sys.stdin.readline().rstrip().split())
graph[x][y] = 1
graph[y][x] = 1
# output
dfs(V)
print()
bfs(V)
์ฐธ๊ณ ๋ธ๋ก๊ทธ ์ฝ๋๋ฅผ ์ฐธ๊ณ ํด์, ๊ฑฐ์ ์ ์ฌํ๋ค.
์์ง์ ์ด๋ ต๋ค,,,