4 5 1 점의 개수, 엣지 개수, 시작 점 번호
1 2
1 3
1 4
2 4
3 4
sys.stdin = open('bfs.txt')
N, M, V = list(map(int, input().split()))
graph = {i+1:[] for i in range(N)}
for m in range(M):
v0, v1 = list(map(int, input().split()))
graph[v0].append(v1)
graph[v1].append(v0)
BFS
- queue를 사용해 구현
- collection deque 사용
import sys
from collections import deque
def bfs(graph, root, visited):
visited[root] = True
que = deque([root])
while que:
v = que.popleft()
print(v, end=' ')
for nextv in graph[v]:
if visited[nextv]:
continue
visited[nextv] = True
que.append(nextv)
DFS
def dfs(graph, root, visited):
stack = [root]
while stack:
v = stack.pop()
if not visited[v]:
visited[v] = True
print(v, end=' ')
for nextv in graph[v]:
if not visited[nextv]:
stack.append(nextv)
def dfs2(graph, root, visited):
if visited[root]:
return
print(root, end=' ')
visited[root] = True
for v in graph[root]:
dfs(graph, v, visited)
return