Python/Coding TEST
[Python] 백준 1260 DFS와 BFS
오늘도개발
2024. 2. 9. 10:54
https://www.acmicpc.net/problem/1260
1260번: DFS와 BFS
첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사
www.acmicpc.net
접근 :
- 기본적인 DFS 와 BFS 관련 문제
- DFS




- BFS


- 코드 구현 :
from collections import deque
import sys
def answer():
N, M, V = map(int, sys.stdin.readline().rstrip().split(' '))
graph = [[] for _ in range(N+1)]
d_visited = [False] * (N+1)
for _ in range(M):
s, e = map(int, sys.stdin.readline().rstrip().split(' '))
graph[s].append(e)
graph[e].append(s)
for i in range(1, N+1):
graph[i].sort()
def dfs(idx, res=''):
res += str(idx) + ' '
d_visited[idx] = True
for next in graph[idx]:
if not d_visited[next]:
res = dfs(next, res)
return res
def bfs(idx):
b_visited = [False] * (N+1)
res = ''
q = deque()
q.append(idx)
res += str(idx) + ' '
b_visited[idx] = True
while q:
idx = q.popleft()
for next in graph[idx]:
if not b_visited[next]:
q.append(next)
res += str(next) + ' '
b_visited[next] = True
return res
print(dfs(V))
print(bfs(V))
answer()