๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 1260๋ฒ
ํ์ด ๊ณผ์
DFS
์ BFS
์ฐ์ฐ์ ๊ตฌํํ๋ ๊ฐ๋จํ ๋ฌธ์ ์
๋๋ค.
๋จผ์ ์
๋ ฅ์ผ๋ก ๋ฐ์ ๊ฐ์ ์ ๋ณด๋ก ๊ทธ๋ํ๋ฅผ ์์ฑํ๊ณ ์ดํ DFS
์ BFS
ํจ์๋ฅผ ํตํด ํ์์ ์ํํฉ๋๋ค.
์ฝ๋
import sys
from collections import deque
sys.setrecursionlimit(10 ** 6)
def bfs(graph, start):
q = deque()
visit = [0] * (N + 1)
order = []
q.append(start)
visit[start] = 1
while q:
here = q.popleft()
order.append(here)
for there in sorted(graph[here]):
if not visit[there]:
visit[there] = 1
q.append(there)
return order
def dfs(graph, here, visit, result):
visit[here] = 1
result.append(here)
for there in sorted(graph[here]):
if not visit[there]:
dfs(graph, there, visit, result)
def make_graph():
graph = [[] for _ in range(N + 1)]
for frm, to in edges:
graph[frm].append(to)
graph[to].append(frm)
return graph
def solution():
graph = make_graph()
dfs_visit = [0] * (N + 1)
dfs_result = []
dfs(graph, V, dfs_visit, dfs_result)
print(*dfs_result)
bfs_result = bfs(graph, V)
print(*bfs_result)
if __name__ == '__main__':
N, M, V = list(map(int, sys.stdin.readline().split()))
edges = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]
solution()
๋ฐ์ํ
'๐ algorithm > boj' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ 17626 - Four Squares (0) | 2021.03.18 |
---|---|
BOJ 1303 - ์ ์ - ์ ํฌ (0) | 2021.03.18 |
BOJ 6550 - ๋ถ๋ถ ๋ฌธ์์ด (0) | 2021.03.18 |
BOJ 10819 - ์ฐจ์ด๋ฅผ ์ต๋๋ก (0) | 2021.03.18 |
BOJ 15240 - Paint bucket (0) | 2021.03.18 |
๐ฌ ๋๊ธ