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()
'Python > Coding TEST' 카테고리의 다른 글
[Python] 백준 1929 소수 구하기 (1) | 2024.02.11 |
---|---|
[Python] 백준 4134 다음 소수 (0) | 2024.02.10 |
[Python] 백준 2485 가로수 (0) | 2024.02.10 |
[Python] 백준 1735 분수 합 (0) | 2024.02.09 |
[Python] 백준 1934 최소공배수 (0) | 2024.02.09 |