์ƒˆ์†Œ์‹

๐Ÿงฎ ์•Œ๊ณ ๋ฆฌ์ฆ˜/-- ๋ฐฑ์ค€ (BOJ) - Python

๋ฐฑ์ค€ (boj) ํŒŒ์ด์ฌ - 1260 : DFS์™€ BFS

  • -

 

๋ฌธ์ œ ๋งํฌ : 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))
Contents

ํฌ์ŠคํŒ… ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ–ˆ์Šต๋‹ˆ๋‹ค

์ด ๊ธ€์ด ๋„์›€์ด ๋˜์—ˆ๋‹ค๋ฉด ๊ณต๊ฐ ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค.