Engineering Note

[BOJ:1260] DFS와 BFS 본문

Problem Solving/BOJ

[BOJ:1260] DFS와 BFS

Software Engineer Kim 2021. 7. 28. 19:59

문제

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

[

1260번: DFS와 BFS

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

www.acmicpc.net

](https://www.acmicpc.net/problem/1260)

코드

import sys
from collections import deque

n,m,v = map(int, sys.stdin.readline().rstrip().split())
dfsVisited = [False]*(n+1)
bfsVisited = [False]*(n+1)
graph = [[0]*(n+1) for _ in range(n+1)]

def dfs(vertex):
    dfsVisited[vertex] = True
    print(vertex, end = " ")

    for i in range(1,n+1):
        if graph[vertex][i] == 1 and not dfsVisited[i]:
            dfs(i)

def bfs(start):
    q = deque()
    print(start,end = " ")
    bfsVisited[start] = True
    q.append(start)

    while q:
        curVertex = q.popleft()

        for i in range(1,n+1):
            if graph[curVertex][i] == 1 and not bfsVisited[i]:
                print(i,end = " ")
                q.append(i)
                bfsVisited[i] = True


## 그래프 생성
for i in range(m):
    a, b = map(int, sys.stdin.readline().rstrip().split())
    graph[a][b] = 1
    graph[b][a] = 1


# dfs
dfs(v)
print("")
# bfs
bfs(v)

문제해결방법

'Problem Solving > BOJ' 카테고리의 다른 글

[BOJ:2231]분해합  (0) 2021.08.11
[BOJ:1436]영화감독 슘  (0) 2021.08.11
[BOJ:16206] 롤케이크  (0) 2021.07.27
[BOJ:1157]단어 공부  (0) 2021.07.27
[BOJ:10809] 알파벳 찾기  (0) 2021.07.27
Comments