알고리즘/CLASS 3
[Python] 백준 1260 DFS와 BFS
한민민
2022. 2. 26. 16:15
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)