Python 구현 코드
from collections import deque
def DFS(start, stack):
dfs_visited[start] = True
for next_node in range(1, N+1):
if dfs_visited[next_node] == False:
if adj_list[start][next_node] == 1 or adj_list[next_node][start]==1 :
stack.append(next_node)
DFS(next_node, stack)
return stack
def BFS(start):
q = deque([start])
visited = [False]*(N+1)
visited[start] = True
while q:
now = q.popleft()
print(now, end=' ')
for next_node in range(1,N+1):
if visited[next_node]==False :
if adj_list[now][next_node] == 1 or adj_list[next_node][now]==1 :
q.append(next_node)
visited[next_node] = True
return
if __name__ == "__main__":
N, M, start = map(int, input().split())
adj_list = [[0]*(N+1) for _ in range(N+1)]
for _ in range(M):
u,v = map(int, input().split())
adj_list[u][v] = 1
adj_list[v][u] = 1
dfs_visited = [False] * (N+1)
print(*DFS(start, [start]))
BFS(start)
'CS Study > Algorithm' 카테고리의 다른 글
[그래프 이론] - Minimum Spanning Tree (최소 신장 트리) (0) | 2021.02.11 |
---|---|
탐색 알고리즘 정리 #3 - 플로이드-워셜 알고리즘(Floyd-Warshall Algorithm) (0) | 2021.02.10 |
탐색 알고리즘 정리 #2 - 다익스트라 알고리즘(Dijkstra algorithm) (0) | 2021.02.10 |