본문 바로가기

알고리즘/백준

[백준 1260][파이썬] DFS와 BFS

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

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

 

from collections import deque
import sys

input = sys.stdin.readline

N, M, V = map(int, input().split())
graph = [[0] * (N+1) for _ in range(N + 1)]
dfs_visited = [0] * (N+1)
bfs_visited = [0] * (N+1)

for _ in range(M):
  m, n = map(int, input().split())
  graph[m][n] = 1
  graph[n][m] = 1

def DFS(v):
  dfs_visited[v] = 1
  print(v, end = ' ')
  for i in range(1, N+1):
    if dfs_visited[i]==0 and graph[v][i]==1:
      DFS(i)

def BFS(v):
  q = deque()
  q.append(v)
  bfs_visited[v] = 1
  while q:
    node = q.popleft()
    print(node, end=' ')
    for i in range(1, N+1):
      if bfs_visited[i]==0 and graph[node][i]==1:
        bfs_visited[i] = 1
        q.append(i)

DFS(V)
print()
BFS(V)