문제 : https://www.acmicpc.net/problem/1260
▶ 코드 ( 큐 ver. )
from collections import deque
n, m, v = map(int, input().split())
s = [[0]*(n+1) for i in range(n+1)]
visited = [0]*(n+1)
for _ in range(m):
a, b = map(int, input().split())
s[a][b] = 1
s[b][a] = 1
def dfs(v):
print(v, end=' ')
visited[v] = 1
for i in range(1, n+1):
if visited[i] == 0 and s[v][i] == 1:
dfs(i)
def bfs(v):
dq = deque([v])
visited[v] = 1
while(dq):
v = dq.popleft()
print(v, end=' ')
for i in range(1, n+1):
if visited[i] == 0 and s[v][i] == 1:
dq.append(i)
visited[i] = 1
dfs(v)
print()
visited = [0]*(n+1) # visited 초기화
bfs(v)
'■코테 중요개념 > BFS' 카테고리의 다른 글
[백준 7576] 토마토 (0) | 2020.05.30 |
---|---|
[백준 2178] 미로 탐색 (0) | 2020.05.29 |
[백준 1012] 유기농 배추 (0) | 2020.05.28 |
[백준 2667] 단지번호붙이기 (0) | 2020.05.28 |
[백준 2606] 바이러스 (0) | 2020.05.28 |