Implementing A* Search Algorithm for 3D Maze Navigation
School
University of Illinois, Urbana Champaign**We aren't endorsed by this school
Course
CS 440
Subject
Computer Science
Date
Dec 12, 2024
Pages
2
Uploaded by siddujunkemail
# search.py# ---------------# Licensing Information: You are free to use or extend this projects for# educational purposes provided that (1) you do not distribute or publish# solutions, (2) you retain this notice, and (3) you provide clear# attribution to the University of Illinois at Urbana-Champaign## Created by Jongdeog Lee (jlee700@illinois.edu) on 09/12/2018"""This file contains search functions."""# Search should return the path and the number of states explored.# The path should be a list of tuples in the form (alpha, beta, gamma) that correspond# to the positions of the path taken by your search algorithm.# Number of states explored should be a number.# maze is a Maze object based on the maze from the file specified by input filename# searchMethod is the search method specified by --method flag (bfs,astar)# You may need to slight change your previous search functions in MP1 since this is3-d mazefrom collections import dequeimport heapq# Search should return the path and the number of states explored.# The path should be a list of MazeState objects that correspond# to the positions of the path taken by your search algorithm.# Number of states explored should be a number.# maze is a Maze object based on the maze from the file specified by input filename# searchMethod is the search method specified by --method flag (astar)# You may need to slight change your previous search functions in MP2 since this is3-d mazedef search(maze, searchMethod):return {"astar": astar,}.get(searchMethod, [])(maze)# TODO: VIdef astar(maze):start_state = maze.get_start()frontier = []heapq.heappush(frontier, (start_state.dist_from_start + start_state.h, start_state))visited_states = {}visited_states[start_state] = None states_explored = 0while frontier:_, current_state = heapq.heappop(frontier)if current_state.is_goal():path = backtrack(visited_states, current_state)return path, states_explored
for neighbor in current_state.get_neighbors():if neighbor not in visited_states or neighbor.dist_from_start < visited_states[neighbor].dist_from_start:visited_states[neighbor] = current_stateheapq.heappush(frontier, (neighbor.dist_from_start + neighbor.h, neighbor))states_explored += 1return None# Go backwards through the pointers in visited_states until you reach the starting state# NOTE: the parent of the starting state is None# TODO: VIdef backtrack(visited_states, current_state):path = []while current_state:path.append(current_state.state) current_state = visited_states[current_state] path.reverse() return path