BFS
๐ โโ๏ธํด๋ํฐ์ผ๋ก ๋ณผ ๋ ํน์ ๊ธ์๋ ์ซ์๊ฐ ํ๋ฉด์ ๋ค ์๋์ค๋ฉด, ํด๋ํฐ ๊ฐ๋ก๋ก ๋๋ฆฌ์๋ฉด ๋ฉ๋๋ค
BFS(Breadth-First Search)
๋ย ๋๋น ์ฐ์ ํ์
์ผ๋ก
์๋ฃ๋ฅผ ์ฐพ์ ๋ "์์ง" ๋ฐฉํฅ์ผ๋ก ์๋ฃ๋ฅผ ๊ฒ์ํ๋ DFS์ ๋ฌ๋ฆฌ, โ์ํโ ๋ฐฉํฅ์ผ๋ก ์๋ฃ๋ฅผ ๊ฒ์ํ๋ค
์ BFS๋ ๋งจ ์ฒ์์์๋ถํฐ ์ํ๋ฐฉํฅ์ผ๋ก ํ์์ ํ๋ค๊ณ ํ์ผ๋ ์๋ ์์์ ๊ฐ์ ๊ฒ์ด๋ค
A->B->C->D->E->F->G->H->I->J ๋ฅผ 1->2->3->4->5->6->7->8->9->10 ๊ฐ์ ์ค๋ฆ์ฐจ์์ด๋ผ ์๊ฐํ์
python ๊ตฌํ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
graph = dict()
graph['Onion'] = ['Rice_ball', 'Poo']
graph['Rice_ball'] = ['Onion', 'Egg']
graph['Poo'] = ['Onion', 'Celery', 'Tofu', 'Pumpkin']
graph['Egg'] = ['Rice_ball', 'Kimchi', 'Peach']
graph['Kimchi'] = ['Egg']
graph['Peach'] = ['Egg']
graph['Celery'] = ['Poo']
graph['Tofu'] = ['Poo']
graph['Pumpkin'] = ['Poo', 'Tomato']
graph['Tomato'] = ['Pumpkin']
def bfs(graph, start_node):
need_visited, visited = [], []
need_visited.append(start_node)
while need_visited:
node = need_visited[0]
del need_visited[0]
# ๋
ธ๋๊ฐ ๋ฐฉ๋ฌธํ์ง ์์๋ค๋ฉด, ๋ฐฉ๋ฌธํ๊ณ visited์ ์ถ๊ฐํด๋ผ
if node not in visited:
visited.append(node)
# ๊ทธ๋ฆฌ๊ณ ํด๋น ๋
ธ๋์ ์ฐ๊ฒฐ๋ ๋ชจ๋ ์ด์๋ค์ need_visited์ ์ถ๊ฐํด๋ผ
# (append๋ ๋จ์ผ์์๋ง ์ถ๊ฐ extend๋ ์ฌ๋ฌ๊ฐ ์ถ๊ฐ)
need_visited.extend(graph[node])
return visited
print(" -> ".join(bfs(graph, 'Onion')))
๐ซ ๋ฐ๊ฒฌํ ๋ฌธ์
ํผ๋๋ฐฑ์ ๋ฐ์๋๋ฐ \(O(E^2)\) ์ฆ ๊ทธ๋ํ ์๊ณ ๋ฆฌ์ฆ์ ์๊ฐ ๋ณต์ก๋๊ฐ ๋๋ฌด ๊ธธ๋ค๊ณ ํ๋ค
์ฆ ์คํ์๊ฐ์ด ๊ฒ๋ ๊ธธ๋ค๋ ๊ฒ์ด๋ค ๊ทธ๋ฆฌํ์ฌ ๊ธฐ์กด ์ฝ๋์์ ์์ ์ ํ๋ค
๊ธฐ์กด ์ฝ๋๋ ๋งค๋ฒ visited ๋ฆฌ์คํธ์์ node๊ฐ ์๋์ง ํ์ธํ๊ณ , ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๋
ธ๋์ธ ๊ฒฝ์ฐ์๋ง visited์ ์ถ๊ฐํด์๋๋ฐ
ํ์ง๋ง ์ด ๋ฐฉ๋ฒ์ ๋งค๋ฒ visited ๋ฆฌ์คํธ๋ฅผ ์ํํ์ฌ ํ์ธํด์ผ ํ๋ฏ๋ก ๋ฆฌ์คํธ์ ํฌ๊ธฐ์ ๋น๋กํ์ฌ ์คํ ์๊ฐ์ด ์ฆ๊ฐํ ์ ์๋ค
๊ทธ๋ฆฌํ์ฌ ๋์ ์ visited๋ฅผ ์งํฉ(set)์ผ๋ก ๊ตฌํํ๋ฉด ๋ ํจ์จ์ ์ผ ์ ์๋ค.
why? -> ์งํฉ์ ์์์ ์กด์ฌ ์ฌ๋ถ๋ฅผ ๋น ๋ฅด๊ฒ ํ์ธํ ์ ์๊ธฐ ๋๋ฌธ์ ๊ฒ์ ์๋๊ฐ ๋น ๋ฆ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
graph = dict()
graph['Onion'] = ['Rice_ball', 'Poo']
graph['Rice_ball'] = ['Onion', 'Egg']
graph['Poo'] = ['Onion', 'Celery', 'Tofu', 'Pumpkin']
graph['Egg'] = ['Rice_ball', 'Kimchi', 'Peach']
graph['Kimchi'] = ['Egg']
graph['Peach'] = ['Egg']
graph['Celery'] = ['Poo']
graph['Tofu'] = ['Poo']
graph['Pumpkin'] = ['Poo', 'Tomato']
graph['Tomato'] = ['Pumpkin']
def bfs(graph, start_node):
need_visited, visited = [], set()
need_visited.append(start_node)
while need_visited:
node = need_visited.pop(0)
if node not in visited:
visited.add(node)
need_visited.extend(graph[node])
return list(visited)
print(" -> ".join(bfs(graph, 'Onion')))