Python/알고리즘 문제풀이

[백준][파이썬] DFS와 BFS

gakko 2022. 1. 25. 12:05

백준 온라인저지 DFS와 BFS

문제풀러 바로가기👇👇👇👇👇👇

DFS와 BFS

 

1260번: DFS와 BFS

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

www.acmicpc.net

 

 

문제풀이


from collections import deque

# 입력받기
n, m, v = map(int, input().split())
graph = [[] for _ in range(n+1)]
for i in range(m):
    a, b = map(int, input().split())
    graph[a].append(b)
    graph[b].append(a)

# 정렬진행
for i in range(1, n+1):
    graph[i].sort()

visit = [False] * (n+1)

def dfs(graph, visited, v):
    visited[v] = True
    print(v, end=" ")
    for i in graph[v]:
        if not visited[i]:
            dfs(graph, visited, i)


def bfs(graph, visited, v):
    queue = deque()
    queue.append(v)
    visited[v] = True

    while queue:
        value = queue.popleft()
        print(value, end=" ")
        for i in graph[value]:
            if not visited[i]:
                visited[i] = True
                queue.append(i)


dfs(graph, visit, v)
visit = [False] * (n+1)
print()
bfs(graph, visit, v)
  • 그냥 dfs와 bfs를 구현하기만 하면되는 문제이다.
  • 숫자 순서대로 탐색을 진행하기 때문에 입력을 받은 후 정렬을 진행해야함.