그래프 구현
n = int(input())
v = int(input())
graph = [[] for i in range(n + 1)]
visited = [0] * (n + 1)
for i in range(v):
a, b = map(int, input().rstrip().split())
graph[a] += [b]
graph[b] += [a]
깊이우선탐색 DFS
Depth First Search
- 첫 노드 방문
- 이웃 노드들에 대해
3-1. 방문하지 않은 노드라면 1-3 반복
3-2. 방문한 노드면 패스
def dfs(v):
visited[v] = 1
for nx in graph[v]:
if visited[nx] == 0:
dfs(nx)
너비우선탐색 BFS
Breadth First Search
- 시작점을 방문 처리 후 큐에 넣기
- 큐가 비어있지 않는 동안 아래 반복
3-1. 가장 먼저 들어온 노드 뽑기
3-2. 해당 노드의 이웃들에 대해 방문하지 않았다면 큐에 넣고 방문 처리
3-3. 방문 했다면 패스
from collections import deque
visited[시작점] = 1
Q = deque([시작점])
while Q:
node = Q.popleft()
for nx in graph[node]:
if visited[nx] == 0:
Q.append(nx)
visited[nx] = 1