
https://www.acmicpc.net/problem/1260

from collections import deque
import sys
N, M, V = map(int, sys.stdin.readline().split())
graph = [[] for _ in range(N+1)]
visited1 = [False] * (N+1)
visited2 = [False] * (N+1)
for i in range(M):
tmp1, tmp2 = map(int, sys.stdin.readline().split())
graph[tmp1].append(tmp2)
graph[tmp2].append(tmp1)
for i in graph:
i.sort()
def dfs(graph, visited, start):
visited[start] = True
print(start, end = ' ')
for i in graph[start]:
if not visited[i]:
dfs(graph, visited, i)
def bfs(graph, visited, start):
queue = deque([start])
visited2[start] = True
while queue:
v = queue.popleft()
print(v, end=' ')
for i in graph[v]:
if not visited2[i]:
queue.append(i)
visited[i] = True
dfs(graph, visited1, V)
print("")
bfs(graph, visited2, V)
- 파이썬 컴프리헨션
- dfs, bfs 구현
'CT' 카테고리의 다른 글
[Python] 백준 2606번 : 바이러스 (1) | 2024.09.09 |
---|---|
[Python] 백준 2178번 : 미로 탐색 (0) | 2024.09.08 |
[Python] 백준 2346번 : 풍선 터뜨리기 (0) | 2024.07.23 |
DFS/BFS - 음료수 얼려 먹기, 미로탈출 (0) | 2024.03.07 |
[Python] 소수 판별 방법, 에라토스테네스의 체 (0) | 2023.09.07 |
댓글