YS's develop story

๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰ (BFS), ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ (DFS) ์ •๋ฆฌ ๋ณธ๋ฌธ

Algorithm

๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰ (BFS), ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ (DFS) ์ •๋ฆฌ

Yusang 2021. 8. 3. 08:07

๐Ÿ‘ฉ‍๐Ÿ’ป ๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰ (BFS), ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ (DFS) ์ •๋ฆฌ with Python

๐Ÿฅ˜ ๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰ (Breadth-First-Search)

Node ๊ฐ™์€ ๋ ˆ๋ฒจ์— ์žˆ๋Š” Node๋“ค (ํ˜•์ œ Node๋“ค)์„ ๋จผ์ € ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค.

 

 

ํŒŒ์ด์ฌ์„ ์ด์šฉํ•œ ๊ทธ๋ž˜ํ”„ ํ‘œํ˜„ ์ฝ”๋“œ

graph = dict()

graph['A'] = ['B', 'C']
graph['B'] = ['A', 'D']
graph['C'] = ['A', 'G', 'H', 'I']
graph['D'] = ['B', 'E', 'F']
graph['E'] = ['D']
graph['F'] = ['D']
graph['G'] = ['C']
graph['H'] = ['C']
graph['I'] = ['C', 'J']
graph['J'] = ['I']

 

 

๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰ (Breadth-First-Search) ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌํ˜„

def BFS(graph, startNode):
    visited,needVisited = list(),list()

    needVisited.append(startNode)

    while needVisited:
        node = needVisited.pop(0)
        if node not in visited:
            visited.append(node)
            needVisited.extend(graph[node])
    return visited

์ž๋ฃŒ๊ตฌ์กฐ Queue๋ฅผ ํ™œ์šฉํ•˜์—ฌ์„œ

visited์™€ needVisited ๋‘ ๊ฐœ์˜ Queue๋ฅผ ์ƒ์„ฑํ•˜์—ฌ์„œ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌํ˜„ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

Queue์˜ ๊ทœํ˜„์€ ๊ฐ„๋‹จํžˆ ํŒŒ์ด์ฌ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ™œ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

 

์ฝ”๋“œ ์‹คํ–‰ ๊ฒฐ๊ณผ

 

๐Ÿณ ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ (Depth-First-Search)

Node์˜ Child๋“ค์„ ๋จผ์ € ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค.

 

 

๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ (Depth-First-Search) ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌํ˜„ 

def BFS(graph, startNode):
    visited,needVisited = list(),list()

    needVisited.append(startNode)

    while needVisited:
        node = needVisited.pop()
        if node not in visited:
            visited.append(node)
            needVisited.extend(graph[node])
    return visited

์ž๋ฃŒ๊ตฌ์กฐ Stack๊ณผ Queue๋ฅผ ํ™œ์šฉํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

needVisited Stack๊ณผ visited Queue, ๋‘ ๊ฐœ์˜ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์ƒ์„ฑํ•˜์—ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ตฌํ˜„ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

Queue์™€ Stack์€ ๊ฐ„๋‹จํžˆ ํŒŒ์ด์ฌ ๋ฆฌ์ŠคํŠธ๋ฅผ ํ™œ์šฉํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

 

์ฝ”๋“œ ์‹คํ–‰ ๊ฒฐ๊ณผ

 

 

BFS ์ž๋ฃŒ๊ตฌ์กฐ๋Š” ๋‘ ๊ฐœ์˜ Queue๋ฅผ ํ™œ์šฉํ•˜๋Š”๋ฐ ๋ฐ˜ํ•ด,

DFS๋Š” Stack๊ณผ Queue๋ฅผ ํ™œ์šฉํ•œ๋‹ค๋Š” ์ฐจ์ด๊ฐ€ ์žˆ์Œ์„ ํ™•์ธํ•ฉ์‹œ๋‹ค!

 

๐Ÿช ์‹œ๊ฐ„ ๋ณต์žก๋„

 

์ผ๋ฐ˜์ ์ธ DFS ์‹œ๊ฐ„ ๋ณต์žก๋„

  • ๋…ธ๋“œ ์ˆ˜: V
  • ๊ฐ„์„  ์ˆ˜: E
    • ์œ„ ์ฝ”๋“œ์—์„œ while need_visit ์€ V + E ๋ฒˆ ๋งŒํผ ์ˆ˜ํ–‰ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.
  • ์‹œ๊ฐ„ ๋ณต์žก๋„: O(V + E)

 

์ผ๋ฐ˜์ ์ธ BFS ์‹œ๊ฐ„ ๋ณต์žก๋„

  • ๋…ธ๋“œ ์ˆ˜: V
  • ๊ฐ„์„  ์ˆ˜: E
    • ์œ„ ์ฝ”๋“œ์—์„œ while need_visit ์€ V + E ๋ฒˆ ๋งŒํผ ์ˆ˜ํ–‰ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.
  • ์‹œ๊ฐ„ ๋ณต์žก๋„: O(V + E)
Comments