🌱 → 🌳

Algorithm) DFS/BFS λ³Έλ¬Έ

Algorithms

Algorithm) DFS/BFS

BAY 2022. 10. 25. 12:49
728x90

κ·Έλž˜ν”„ 탐색 μ•Œκ³ λ¦¬μ¦˜: DFS/BFS

탐색(search)μ΄λž€ λ§Žμ€ μ–‘μ˜ 데이터 μ€‘μ—μ„œ μ›ν•˜λŠ” 데이터λ₯Ό μ°ΎλŠ” κ³Όμ •

λŒ€ν‘œμ μΈ κ·Έλž˜ν”„ 탐색 μ•Œκ³ λ¦¬μ¦˜μœΌλ‘œ DFS/BFSκ°€ 쑴재

 

자료ꡬ쑰

μŠ€νƒ(μ„ μž…ν›„μΆœ)

λ¨Όμ € λ“€μ–΄ 온 데이터가 λ‚˜μ€‘μ— λ‚˜κ°€λŠ” ν˜•μ‹μ˜ 자료ꡬ쑰

μ˜ˆμ‹œ) λ°•μŠ€ μŒ“κΈ°

 

DFS method μ •μ˜ 

def dfs(graph, v, visited):
    visited[v] = True
    print(v, end=' ')
    for i in graph[v]:
        if not visited[i]:
            dfs(graph, i, visited)
            
graph = [
    [],
    [2,3,8],
    [1,7],
    [1,4,5],
    [3,5],
    [3,4],
    [7],
    [2,6,8],
    [1,7]
]

visited = [False] * 9
dfs(graph, 1, visited)

 

BFS method μ •μ˜ 

κ°„μ„  λΉ„μš©μ΄ λͺ¨λ‘ 같을 λ•Œ μ΅œλ‹¨κ±°λ¦¬λ₯Ό νƒμƒ‰ν•˜κΈ° μœ„ν•΄ 쓰일 수 μžˆλŠ” μ•Œκ³ λ¦¬μ¦˜

from collections import deque

# BFS λ©”μ„œλ“œ μ •μ˜ 
def bfs(graph, start, visited):
    queue = deque([start])
    visited[start] = True
    while queue:
        v = queue.popleft()
        print(v, end=' ')
        for i in graph[v]:
            if not visited[i]:
                queue.append(i)
                visited[i] = True
graph = [
    [],
    [2,3,8],
    [1,7],
    [1,4,5],
    [3,5],
    [3,4],
    [7],
    [2,6,8],
    [1,7]
]

visited = [False] * 9
bfs(graph, 1, visited)

 

728x90

'Algorithms' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

Algorithm) Dynamic Programming  (1) 2022.10.25
Algorithm) Binary Search(이진탐색)  (0) 2022.10.25
Algorithm) Greedy  (0) 2022.10.25
Algorithm) μ•Œκ³ λ¦¬μ¦˜ μ„±λŠ₯  (0) 2022.10.25
[λ°±μ€€] 18870번: μ’Œν‘œ μ••μΆ• python  (0) 2022.10.10