[백준]DFS와 BFS(1260) - python

당고누나·2025년 5월 14일
0

coding-test

목록 보기
52/52
post-thumbnail

✏️ 문제

그래프를 DFS로 탐색한 결과와 BFS로 탐색한 결과를 출력하는 프로그램을 작성하시오. 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문하고, 더 이상 방문할 수 있는 점이 없는 경우 종료한다. 정점 번호는 1번부터 N번까지이다.


🎈 입력형식

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사이에 여러 개의 간선이 있을 수 있다. 입력으로 주어지는 간선은 양방향이다.

🎈 출력형식

첫째 줄에 DFS를 수행한 결과를, 그 다음 줄에는 BFS를 수행한 결과를 출력한다. V부터 방문된 점을 순서대로 출력하면 된다.

🎈 입출력 예

<입력>
4 5 1
1 2
1 3
1 4
2 4
3 4

<출력>
1 2 4 3
1 2 3 4


👩‍💻 내 코드

import sys
from collections import deque
input = sys.stdin.readline

def dfs(graph, node, visited):
  visited[node] = 1
  print(node, end=' ')
  for neighbor in sorted(graph[node]):
    if not visited[neighbor]:
      dfs(graph, neighbor, visited)

def bfs(graph, root):
  visited = [0] * (len(graph))
  queue = deque([root])
  visited[root] = 1

  while queue:
    node = queue.popleft()
    print(node, end=' ')
    for neighbor in sorted(graph[node]):
      if not visited[neighbor]:
        visited[neighbor] = 1
        queue.append(neighbor)

if __name__ == "__main__":
  n, m, root = map(int, input().split())
  graph = [[] for _ in range(n+1)]

  for i in range(m):
    fr, to = map(int, input().split())
    graph[fr].append(to)
    graph[to].append(fr)

  dfs_visited = [0] * (n+1)
  
  dfs(graph, root, dfs_visited)
  print()
  bfs(graph, root)

💡 새롭게 배운 것

  • deque 시간복잡도 O(1)
  • list 시간복잡도 O(n)
  • DFS는 LIFO, BFS는 FIFO 이다.
profile
초심 잃지 말기 🙂

0개의 댓글