1260 DFS와 BFS

코린이서현이·2024년 3월 24일
0

문제

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

입력

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

4 5 1
1 2
1 3
1 4
2 4
3 4

출력

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

1 2 4 3
1 2 3 4

문제풀이

import sys
from collections import deque

def dfs(graph,start):
    DFS = deque()   #결과
    visit_list = [] #방문 리스트

    stack = deque()
    stack.append(start)

    while stack:
        target_node = stack.pop()
        if target_node not in visit_list:
            DFS.append(target_node)
            visit_list.append(target_node)
            connection_nodes = sorted(graph[target_node -1], reverse= True)
            for i in connection_nodes:
                if i not in visit_list:
                    stack.append(i)

    return DFS

def bfs(graph,start):
    BFS = deque()   #결과
    visit_list = [] #방문 리스트

    queue = deque()
    queue.append(start)

    while queue:
        target_node = queue.popleft()
        if target_node not in visit_list:
            BFS.append(target_node)
            visit_list.append(target_node)
            connection_nodes = sorted(graph[target_node -1])
            for i in connection_nodes:
                if i not in visit_list:
                    queue.append(i)

    return BFS

n,m,start =  map(int, sys.stdin.readline().strip().split(" "))
graph = [[] for i in range(n)]

for i in range(m):
    a = list(map(int,sys.stdin.readline().strip().split(" ")))
    graph[a[0]-1].append(a[1])
    graph[a[1]-1].append(a[0])

DFS = dfs(graph,start)
DFS = ' '.join(list(map(str,DFS)))
print(DFS)

BFS = bfs(graph, start)
BFS = ' '.join(list(map(str,BFS)))
print(BFS)
profile
24년도까지 프로젝트 두개를 마치고 25년에는 개발 팀장을 할 수 있는 실력이 되자!

0개의 댓글