BaekJoon Algorithm/Python

[백준알고리즘 - 1260] DFS와 BFS (Python)

Loafly 2021. 3. 20. 00:04
728x90

(1) 문제

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

 


(2) 입력

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

(3) 출력

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

 


(4) 예제 입력 및 출력


(5) 코드

import sys
import collections
point, line, start_point = map(int, sys.stdin.readline().split())

graph = {

}

def BFS(start_point, graph, check):
    queue = collections.deque([start_point])
    while queue:
        cur_value = queue.popleft()
        if check[cur_value]:
            continue
        else:
            check[cur_value] = True
            for cur_line in graph[cur_value]:
                if not check[cur_line]:
                    queue.append(cur_line)
            print(cur_value, end= ' ')

def DFS(start_point, graph, check):

    if check[start_point]:
        return
    else:
        print(start_point, end=' ')
        check[start_point] = True
        for cur_line in graph[start_point]:
            if not check[cur_line]:
                DFS(cur_line, graph, check)

for i in range(point):
    graph[i + 1] = []

for i in range(line):
    start, end = map(int, sys.stdin.readline().split())
    if start in graph:
        graph[start].append(end)
        graph[end].append(start)

for array in graph:
    graph[array].sort()

check = [False] * (point + 1)
DFS(start_point, graph, check)
print()
check = [False] * (point + 1)
BFS(start_point, graph, check)

(6) 실행결과


반응형