๋ฐฑ์ค€ & ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/DFS & BFS

[๋ฐฑ์ค€ 1260] [dfs/bfs] BFS์™€ DFS โ—

_cactus 2021. 4. 23. 00:06
๋ฐ˜์‘ํ˜•

๐Ÿ’ป ๋ฐฑ์ค€ 1260๋ฒˆ [BFS์™€ DFS]

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 = 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)
๋ฉ”๋ชจ๋ฆฌ์‹œ๊ฐ„์–ธ์–ด์ฝ”๋“œ๊ธธ์ด
35284KB616msPython 3990B

 

์ฒ˜์Œ์— ์‹ค์ˆ˜ํ–ˆ๋˜ ํฌ์ธํŠธ๋Š” 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
๋ฐ˜์‘ํ˜•