Question: Need help with a BFS Maze in Python, I have somewhat of a counter method working but am struggling on the fill in spots. Thanks!
Need help with a BFS Maze in Python, I have somewhat of a counter method working but am struggling on the fill in spots. Thanks! import time class Maze(): """A pathfinding problem.""" def __init__(self, grid, location): """Instances differ by their current agent locations.""" self.grid = grid self.location = location def display(self): """Print the maze, marking the current agent location.""" for r in range(len(self.grid)): for c in range(len(self.grid[r])): if (r, c) == self.location: print('\033[96m*\x1b[0m', end=' ') # print a blue * else: print(self.grid[r][c], end=' ') # prints a space or wall print() print() def moves(self): """Return a list of possible moves given the current agent location.""" # YOU FILL THIS IN def neighbor(self, move): """Return another Maze instance with a move made.""" # YOU FILL THIS IN class Agent(): """Knows how to find the exit to a maze with BFS.""" def bfs(self, maze, goal): """Return an ordered list of moves to get the maze to match the goal.""" # YOU FILL THIS IN theFrontier = [maze] # frontier explored = [maze.location] # explored nodes # while loop that checks if there is anything on frontier while len(theFrontier) > 0: # sets the new frontier list newFrontier = [] # loop through the frontier for maze in newFrontier: for move in maze.moves(): new_maze = maze.neighbor(move) if new_maze.location == goal.location: thePath = [] return thePath newFrontier.pop(0) if (new_maze != explored): explored.append(new_maze) def main(): """Create a maze, solve it with BFS, and console-animate.""" grid = ["XXXXXXXXXXXXXXXXXXXX", "X X X X", "X XXXXX XXXX XXX XXX", "X X X X X", "X X XXX XXXXXX X X X", "X X X X X X", "X XXX XXXXXX XXXXX X", "X XXX X X X X", "X XXX XXXXX", "XXXXX XXXXXX X", "X XXX X X X X X", "XXX XXX X X XXXX X X", "X X X XX X X X", "XXXXX XXXX X XXX", "X X XXX X X", "X XXXXX X XXXX XXX X", "X X X X X X", "X X XXXXXX X XXXXX X", "X X X", "XXXXXXXXXXXXXXXXXX X"] maze = Maze(grid, (1, 1)) maze.display() agent = Agent() goal = Maze(grid, (19, 18)) path = agent.bfs(maze, goal) while path: move = path.pop(0) maze = maze.neighbor(move) time.sleep(0.50) maze.display() if __name__ == '__main__': main() Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
