๋ฐ์ํ
๐ป ๋ฐฑ์ค 1260๋ฒ [BFS์ DFS]
ํ์ด)
# ์ต์ข ์ ์ถ from collections import deque n,m,v = map(int,input().split()) input_lst = sorted([list(map(int,input().split())) for _ in range(m)], key = lambda x : (x[0],x[1])) edge_lst = [[] for _ in range(n+1)] for v1,v2 in input_lst : edge_lst[v1].append(v2) edge_lst[v2].append(v1) visited = [0]*(n+1) dfs_lst = [] def dfs(v,dfs_lst) : # 1. ๋ฐฉ๋ฌธํ ๋ ธ๋์ธ์ง ํ์ธ if visited[v] == 0 : dfs_lst.append(v) # ๋ฐฉ๋ฌธ์ฒ๋ฆฌ visited[v] = 1 # 2. ์ธ์ ํ ๋ ธ๋ ์ํ for v2 in sorted(edge_lst[v]) : dfs(v2,dfs_lst) return dfs_lst print(*dfs(v,dfs_lst)) visited = [0]*(n+1) q = deque() # ์ฒซ ๋ ธ๋ ํ์ฝ์ & ๋ฐฉ๋ฌธ์ฒ๋ฆฌ q.append(v) visited[v] = 1 bfs_lst = [v] while 1 : for v2 in sorted(edge_lst[v]) : if visited[v2] == 0 : q.append(v2) bfs_lst.append(v2) visited[v2] = 1 if len(q) == 0: break v = q.popleft() print(*bfs_lst)
๋ฉ๋ชจ๋ฆฌ | ์๊ฐ | ์ธ์ด | ์ฝ๋๊ธธ์ด |
35284KB | 616ms | Python 3 | 990B |
์ฒ์์ ์ค์ํ๋ ํฌ์ธํธ๋ edge_lst๋ฅผ ๋ง๋ค๋ ์ธ์ ๋ ธ๋๋ค ๋ฆฌ์คํธ๊ฐ sorting์ด ์๋์ด ์๋ ๊ฒ
๊ทธ๋์ dfs/bfs ๊ณผ์ ์์์ ์ธ์ ๋ ธ๋ ํ์ธํ ๋ sorted() ํจ์๋ฅผ ์ด์ฉํ์ฌ sorting์ ํ๊ณ ์ธ์ ๋ ธ๋๋ค์ ๊ฐ์ด ์์ ๊ฒ๋ถํฐ ํ์ธํด๋๊ฐ๋ ๊ณผ์ ์ ๊ฑฐ์ณค๋ค
์ด๋ฅผ ํ์ธํ ์ ์๊ฒ ๋์์ค ๋ฐ๋ก๋ ๋ค์๊ณผ ๊ฐ๋ค
# input 10 10 4 5 4 6 4 6 8 8 9 1 10 2 10 10 3 8 2 1 7 4 10 # output 4 5 6 8 2 10 1 7 3 9 4 5 6 10 8 1 2 3 9 7
BFS์ DFS ๊ตฌํํ๊ธฐ. ๊ธฐ๋ณธ ์ค์ ๊ธฐ๋ณธ์ด๋ ์ด๊ฒ๋ถํฐ. โผ
728x90
๋ฐ์ํ
'๋ฐฑ์ค & ํ๋ก๊ทธ๋๋จธ์ค > DFS & BFS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค] DFS/BFS level2 ํ๊ฒ๋๋ฒ (0) | 2022.03.24 |
---|---|
[๋ฐฑ์ค 1012] [dfs/bfs] ์ ๊ธฐ๋ ๋ฐฐ์ถ (0) | 2021.04.29 |
[๋ฐฑ์ค 1012] [dfs/bfs] ์ ๊ธฐ๋ ๋ฐฐ์ถ (0) | 2021.04.24 |
[๋ฐฑ์ค 2667] [dfs/bfs] ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ (0) | 2021.04.23 |
[๋ฐฑ์ค 2178] [dfs/bfs] ๋ฏธ๋กํ์ (0) | 2021.04.23 |
[๋ฐฑ์ค 2606] [dfs/bfs] ๋ฐ์ด๋ฌ์ค (0) | 2021.04.22 |
[๋ฐฑ์ค 2331] [dfs] ๋ฐ๋ณต์์ด (0) | 2021.04.22 |