-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5-9.py
More file actions
44 lines (36 loc) · 1002 Bytes
/
5-9.py
File metadata and controls
44 lines (36 loc) · 1002 Bytes
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
31
32
33
34
35
36
37
38
39
40
41
42
#CH5 BFS&DFS
#예제 5-9
# BFS
from collections import deque
#BFS 메서드 정의
def bfs(graph, start, visited):
#큐(Queue) 구현을 위해 deque 라이브러리 사용
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
#각 노드가 연결된 정보를 리스트 자료형으로 표현(2차원 리스트)
graph = [
[],
[2,3,8],
[1,7],
[1,4,5],
[3,5],
[3,4],
[7],
[2,6,8],
[1,7]
]
#각 노드가 방문된 정보를 리스트 자료형으로 표현(1차원 리스트)
visited = [False] *9
#정의된 bfs 함수 호출
bfs(graph,1,visited)