DFS/ BFS
πλνμ κ·Έλν(Graph) νμ μκ³ λ¦¬μ¦μΈ DFS/BFSλ₯Ό μκ°ν©λλ€.
κ·Έλν(Graph)λ λκΉ?
κ·Έλν(Graph) λ μ μ (
vertex
, λ Έλ)κ³Ό κ°μ (edge
)λ‘ κ΅¬μ±λ μ νν(finite) μλ£κ΅¬μ‘° μ λλ€.λ μ μ (λ Έλ)κ° κ°μ μΌλ‘ μ°κ²°λλ©΄ 'λ λ Έλλ μΈμ (Adjacent)νλ€' λΌκ³ ν©λλ€.
νμ΄μ€λΆ, μΈμ€νκ·Έλ¨ κ°μ μμ λ€νΈμν¬μ λ°μ΄ν°λ² μ΄μ€κ° κ·Έλν κ΅¬μ‘°λ‘ λ§λ€μ΄μ Έ μμ΅λλ€. κ·Έλν ꡬ쑰λ₯Ό ν΅ν΄ μ¬λλ€(
node
) μ¬μ΄μ κ΄κ³(edge
) λ₯Ό μ½κ² νμν μ μμ΅λλ€.
κ·Έλν νμ
νλμ μ μ (λ Έλ)μμ λͺ¨λ λ Έλλ₯Ό ν λ²μ© νμ(λ°©λ¬Έ) νλ κ²μ λ§ν©λλ€.
DFS(Depth-First Search, κΉμ΄ μ°μ νμ)
κ·Έλνμ μ΅λ κΉμ΄κΉμ§ νμν ν, λ€λ₯Έ κ²½λ‘λ‘ μ΄λνμ¬ νμνλ μκ³ λ¦¬μ¦μ λλ€.
μμ λ Έλμμ μ΅λν λ©λ¦¬ μλ λ Έλ λ₯Ό μ°μ νμν©λλ€.
DFSλ₯Ό νμ©νμ¬ λ―Έλ‘μ°ΎκΈ° λ¬Έμ λ₯Ό ν΄κ²°ν μ μμ΅λλ€. λ―Έλ‘ μμ κΈΈμ κ°μ (
edge
)μΌλ‘, λ§λ€λ₯Έ μ§μ μ μ μ (node
)μΌλ‘ λ³΄κ³ λ―Έλ‘μ λμ°©μ μ λλ¬ν λκΉμ§ κ° κ²½λ‘μ μ΅λ κΉμ΄κΉμ§ νμν©λλ€. νμ¬ μ νν κ²½λ‘κ° λ§λ€λ₯Έ 골λͺ©μ λΆλͺνλ©΄ λλμκ°μ(λ°±νΈλνΉ) λ€λ₯Έ κ²½λ‘λ₯Ό νμν©λλ€.μ€νκ³Ό μ¬κ·ν¨μλ₯Ό μ΄μ©νμ¬ κ΅¬νν μ μμ΅λλ€.
DFS ꡬν μμ
BFS(-First Search, λλΉ μ°μ νμ)
κ·Έλνμ κ·Όμ λ ΈλλΆν° νμν ν, λ€λ₯Έ κ²½λ‘λ‘ μ΄λνμ¬ νμνλ μκ³ λ¦¬μ¦μ λλ€.
μμ λ Έλμμ μ΅λν κ°κΉμ΄ λ Έλ(μ΄μ λ Έλ) λΆν° μ°μ νμν©λλ€.
BFSλ P2P νμΌ λ€νΈμν¬μμ νΌμ΄(peer) λ Έλλ₯Ό νμν λ νμ©ν μ μμ΅λλ€. BFSλ₯Ό νμ©ν΄ κ°μ₯ κ°κΉμ΄ μ΄μ λ Έλλ§ λΉ λ₯΄κ² νμν μ μμ΅λλ€.
νλ₯Ό μ΄μ©νμ¬ κ΅¬νν μ μμ΅λλ€.
BFS ꡬν μμ
β» Big-O
μκ° λ³΅μ‘λλ λ νμ μκ³ λ¦¬μ¦ λͺ¨λ
O(N)
(N: κ·Έλν λ Έλμ κ°μ) μ λλ€.κ³΅κ° λ³΅μ‘λλ DFSλ³΄λ€ BFS μλμ μΌλ‘ ν½λλ€.(λ λ§μ λ©λͺ¨λ¦¬ μ°¨μ§)
π‘μ 리
BFSλ νμν΄μΌ ν κ·Έλνμ κΉμ΄κ° λ Έλλ§λ€ λ€λ₯΄κ±°λ λ¨μΌ λλ΅μ΄ νμν κ²½μ°(μ΅λ¨ κ²½λ‘ κ΅¬νκΈ° λ±)μ μ 리ν©λλ€.
κ·Έλνμ λͺ¨λ λ Έλλ₯Ό νμν΄μΌ νλ€λ©΄ DFSκ° λ μ’μ λ°©λ²μΌ μ μμ΅λλ€.
Reference
Graphs: breadth-first search | freeCodeCamp
Last updated