쏘ing
[Python] 백준 1260 DFS와 BFS 본문
https://www.acmicpc.net/problem/1260

풀이
from collections import deque
def dfs(graph, V, visitied):
visited[V] = True
print(V, end = " ")
for i in graph[V]:
if not visited[i]:
dfs(graph, i, visited)
def bfs(graph, start, visitied):
queue = deque([start])
visited[start] = True
while queue:
V = queue.popleft()
print(V, end=" ")
for i in graph[V]:
if not visited[i]:
queue.append(i)
visited[i] = True
N, M, V = map(int, input().split())
graph = [[] for _ in range(N + 1)]
for _ in range (M):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
for i in range(1, N + 1):
graph[i].sort()
visited = [False] * (N + 1)
dfs(graph, V, visited)
visited = [False] * (N + 1)
print()
bfs(graph, V, visited)
'알고리즘 > CLASS 3' 카테고리의 다른 글
[Python] 백준 1931 회의실 배정 (0) | 2022.02.26 |
---|---|
[Python] 백준 2606 바이러스 (0) | 2022.02.26 |
[Python] 백준 11726 2 x n 타일링 (0) | 2022.02.26 |
[Python] 백준 11286 절댓값 힙 (0) | 2022.02.23 |
[Python] 백준 1927 최소 힙 (0) | 2022.02.22 |
Comments