Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

pls write python code for maze solving

  1. User

    pls write python code for maze solving

  2. Assistant

    Certainly! Here's an example of Python code that solves a maze using the Depth First Search algorithm:

    # Maze dimensions
    MAZE_WIDTH = 5
    MAZE_HEIGHT = 5
    
    # Maze representation
    maze = [
        [0, 1, 0, 0, 0],
        [0, 1, 1, 1, 0],
        [0, 0, 1, 0, 0],
        [0, 1, 0, 1, 1],
        [0, 0, 0, 0, 0]
    ]
    
    # Visited cells
    visited = [[False for _ in range(MAZE_WIDTH)] for _ in range(MAZE_HEIGHT)]
    
    # Possible movements
    movements = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    
    # Recursive function to solve the maze
    def dfs(row, col):
        # Check if we reached the goal
        if row == MAZE_HEIGHT-1 and col == MAZE_WIDTH-1:
            return True
        
        visited[row][col] = True
        
        # Try all possible movements
        for move in movements:
            new_row = row + move[0]
            new_col = col + move[1]
            
            # Check if the new position is valid
            if (0 <= new_row < MAZE_HEIGHT and 0 <= new_col < MAZE_WIDTH and
                maze[new_row][new_col] == 0 and not visited[new_row][new_col]):
                
                # Recursive call
                if dfs(new_row, new_col):
                    return True
        
        return False
    
    # Solve the maze starting from position (0, 0)
    if dfs(0, 0):
        print("Maze solved!")
    else:
        print("Maze cannot be solved.")
    

    This code represents a sample 5x5 maze as a 2D matrix. The Depth First Search algorithm recursively explores the maze, trying all possible movements until it reaches the goal cell. The algorithm marks visited cells to prevent infinite loops and backtracking. If the maze can be solved, it will print "Maze solved!"; otherwise, it will print "Maze cannot be solved." You can modify the maze variable to represent different mazes.