본문 바로가기
백준 & 프로그래머스

백준.DFS와 BFS.1260.py

by concho 2023. 9. 23.

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

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

import sys
import queue
def solution_dfs(graph, start):
    visit, visited, resalt = [start], set(), []
    
    while visit:
        node = visit.pop()
        if node not in visited:
            visited.add(node)
            resalt.append(str(node))
            visit.extend(sorted(graph[node],reverse=True))

    return ' '.join(resalt)

def solution_bfs(graph, start):
    visit, visited, resalt = queue.Queue(), set(), []
    visit.put(start)
    while visit.qsize() > 0:
        node = visit.get()
        if node not in visited:
            visited.add(node)
            resalt.append(str(node))
            for n in sorted(graph[node]): visit.put(n)
    return ' '.join(resalt)

if __name__ == '__main__':
    n, m, v = map(int, sys.stdin.readline().rstrip().split())
    graph = dict()
    for _ in range(m):
        a, b = map(int, sys.stdin.readline().rstrip().split())
        if a in graph:
            graph[a].append(b)
        else:
            graph[a] = [b]
        if b in graph:
            graph[b].append(a)
        else:
            graph[b] = [a]
            
    if graph.get(v, False): 
        resalt_dfs = solution_dfs(graph, v)
        print(resalt_dfs)
        resalt_bfs = solution_bfs(graph, v)
        print(resalt_bfs)
    else: # 시작 정점이 다른 정점과 연결이 되어있지 않을 경우
        print(f'{v}\n{v}')

댓글