
너비 우선 탐색 알고리즘을 코드로 나타내면 다음과 같다.
from collections import deque # deque 모듈을 가져옴
import maze_puzzle as mp # maze_puzzle 모듈을 mp로 가져옴
def run_bfs(maze_puzzle, current_point, visited_points):
queue = deque() # 빈 deque 생성
queue.append(current_point) # 시작 지점을 큐에 추가
while queue: # 큐가 비어있지 않은 동안 반복
current_point = queue.popleft() # 큐의 왼쪽에서 현재 지점을 추출하여 꺼냄
neighbors = maze_puzzle.get_neighbors(current_point) # 현재 지점의 이웃 지점들을 가져옴
for neighbor in neighbors: # 이웃 지점들에 대해 반복
if not is_in_visited_points(neighbor, visited_points): # 이웃 지점이 방문한 지점이 아니라면
neighbor.set_parent(current_point) # 이웃 지점의 부모를 현재 지점으로 설정
queue.append(neighbor) # 이웃 지점을 큐에 추가
visited_points.append(neighbor) # 이웃 지점을 방문한 지점 리스트에 추가
if maze_puzzle.get_current_point_value(neighbor) == '*': # 이웃 지점이 목적지인 경우
return neighbor # 목적지 반환
return "No Path to the goal found." # 목적지까지의 경로가 없는 경우 메시지 반환
def is_in_visited_points(current_point, visited_points):
for visited_point in visited_points: # 방문한 지점 리스트에 대해 반복
if current_point.x == visited_point.x and current_point.y == visited_point.y: # 현재 지점이 방문한 지점이면
return True # True 반환
return False # 아니면 False 반환
print("--Breath-first Search--")
maze_game_main = mp.MazePuzzle() # MazePuzzle 클래스의 인스턴스 생성
starting_point = mp.Point(2,2) # 시작 지점 설정
outcome = run_bfs(maze_game_main, starting_point, []) # BFS 알고리즘으로 미로 탐색
bfs_path = mp.get_path(outcome) # 경로 추출
print("Path Length:", len(bfs_path)) # 경로 길이 출력
maze_game_main.overlay_points_on_map(bfs_path) # 미로 지도에 경로 표시
print("Path Cost : ", mp.get_path_cost(outcome)) # 경로 비용 출력
for point in bfs_path: # 경로 상의 각 지점에 대해
print("Point:", point.x, ',', point.y) # 해당 지점의 좌표 출력
실행 결과
--Breath-first Search--
Path Length: 8
@0000
@###0
@#0#0
@#@00
@@@00
Path Cost : 16
Point: 0 , 0
Point: 1 , 0
Point: 2 , 0
Point: 3 , 0
Point: 4 , 0
Point: 4 , 1
Point: 4 , 2
Point: 3 , 2