백준_1260_DFS와 BFS

임정민·2023년 1월 9일
2

알고리즘 문제풀이

목록 보기
16/173
post-thumbnail

코딩테스트 연습 스터디 진행중 입니다. ✍✍✍
Notion : https://www.notion.so/1c911ca6572e4513bd8ed091aa508d67

문제

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

[나의 풀이]

from collections import deque

def getData():
    
    N, M, V = list(map(int,input().split()))
    graph = [set()for i in range(N+1)]
    for _ in range(1,M+1): # i= 1~5
        connect = list(map(int,input().split()))
        graph[connect[0]].add(connect[1])
        graph[connect[1]].add(connect[0])
    return graph,V
graph,V = getData()

def DFS(graph,V):
    
    DFS_visited = []
    stack = [V]
    
    while stack:
        n = stack.pop()
        if n not in DFS_visited:
            DFS_visited.append(n)
            stack += sorted(list(graph[n] - set(DFS_visited)),reverse=True) 
    return DFS_visited                                                      
                                                                            
DFS_visited = DFS(graph,V)                                                  

def BFS(graph,V):
    
    BFS_visited = []
    queue = deque([V])
    
    while queue:
        n = queue.popleft()
        if n not in BFS_visited:
            BFS_visited.append(n)
            queue += sorted(graph[n] - set(BFS_visited)) 
    return BFS_visited                           
                                                
BFS_visited = BFS(graph,V)

print(*DFS_visited)
print(*BFS_visited)

DFS 와 BFS 알고리즘을 처음 접하여 개념을 먼저 이해하고 풀었다. set() 자료형 앞에 *(Asterisk)를 붙혀 괄호,쉼표 없이 바로 출력하였다.

profile
https://github.com/min731

0개의 댓글