🧮 PS

백준 (boj) 파이썬 - 1260 : DFS와 BFS

Newmon 2021. 6. 22. 19:36

 

문제 링크 : https://www.acmicpc.net/problem/1260

 

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 = list(map(int, input().split()))
matrix = [[0 for i in range(N+1)] for i in range(N+1)]
dfs_answer = []
bfs_answer = []
visited = [False for i in range(N + 1)]
visit = [False for i in range(N + 1)]

## 인접 행렬 방식으로 입력받기.
for i in range(M):
	x, y = map(int, input().split())
	matrix[x][y] = matrix[y][x] = 1

def dfs(V) :
	dfs_answer.append(str(V))
	visited[V] = True
	for i in range(1, N + 1) :
		if visited[i] == False and matrix[V][i] == 1 :
			dfs(i)

queue = deque()

def bfs(V):
	visit[V] = True
	queue.append(V)

	while (queue) :
		V = queue.popleft()
		bfs_answer.append(str(V))

		for i in range(1, N+1):
			if visit[i] == False and matrix[V][i] == 1 :
				queue.append(i)
				visit[i] = True

dfs(V)
bfs(V)
print(" ".join(dfs_answer))
print(" ".join(bfs_answer))