Dizzy999
dizzy-theme
Dizzy999
전체 방문자
오늘
어제
  • 분류 전체보기 (34)
    • Machine Learning (1)
      • 논문 리뷰 (0)
      • 수학통계 이론 (1)
      • 짧은글 (0)
    • 알고리즘 (22)
      • 알고리즘 이론 (1)
      • 알고리즘 문제 (20)
      • 짧은글 (1)
    • 프로그램 (2)
      • 프로그래밍 용어 및 상식 (1)
      • C++ (1)
    • 미니프로젝트 (0)
      • Moon Tracker (0)
    • Theme (0)
      • 짧은글 (0)
    • 아두이노&라즈베리파이 (1)
      • 아두이노 (0)
      • 라즈베리파이 (1)
    • Miscellaneous (3)
      • 이과가 이해한 Color (3)
    • OpenCV (0)
      • Tutorial (0)
    • Manim (5)
      • Tutorial (5)

블로그 메뉴

  • 홈
  • 방명록
  • 태그

공지사항

인기 글

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Dizzy999

dizzy-theme

알고리즘/알고리즘 문제

[백준-1260] DFS와 BFS - Python

2021. 12. 8. 08:23

 

 

문제 : [백준-1260] DFS와 BFS - Python

출처 : 백준

 

문제

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

 


   사용한 알고리즘  

더보기

DFS

BFS


 


   Python Code    

#############################################################################
# 1260
#############################################################################

import sys
import collections

sys.stdin = open("input.txt", "r")

N , M , start_node = list(map(int , input().split(" ")))

#### graph 만들기
graph = collections.defaultdict(list)
for _ in range(M):
    node_start , node_end = list(map(int , input().split(" ")))
    if node_end not in graph[node_start]:
        graph[node_start].append(node_end)
    if node_start not in graph[node_end]:
        graph[node_end].append(node_start)
    graph[node_start].sort()
    graph[node_end].sort()
####

DFS_visited =  []
def DFS(graph , start_node):
    DFS_visited.append(start_node)
    for node in graph[start_node]:
        if node not in DFS_visited:
            DFS(graph,node)

BFS_visited = []
def BFS(start_node):
    Q = collections.deque([])
    Q.append(start_node)
    BFS_visited.append(start_node)
    while Q:
        x = Q.popleft()
        for node in graph[x]:
            if node not in BFS_visited:
                Q.append(node)
                BFS_visited.append(node)



DFS(graph,start_node)
# for i in list(graph.keys()):
#     if i not in DFS_visited:
#         DFS(graph, i)
print(*DFS_visited)

BFS(start_node)
# for i in list(graph.keys()):
#     if i not in BFS_visited:
#         BFS(i)
print(*BFS_visited)

 

 

 

 

반응형

'알고리즘 > 알고리즘 문제' 카테고리의 다른 글

[백준-2468] 안전 영역 - Python  (0) 2021.12.08
[백준-2644] 촌수계산 - Python  (0) 2021.12.08
[백준-11724] 연결 요소의 개수 - Python  (0) 2021.12.07
[백준-2583] 영역 구하기 - Python  (0) 2021.12.07
[백준-4485] 녹색 옷 입은 애가 젤다지? - Python  (0) 2021.11.17
    '알고리즘/알고리즘 문제' 카테고리의 다른 글
    • [백준-2468] 안전 영역 - Python
    • [백준-2644] 촌수계산 - Python
    • [백준-11724] 연결 요소의 개수 - Python
    • [백준-2583] 영역 구하기 - Python
    Dizzy999
    Dizzy999

    티스토리툴바