Python

 

Introduction

A maze is a complex, branching puzzle designed to confuse or challenge the solver. A maze solver is a program that finds the path from the starting point to the exit within the maze. In this guide, we will create a Python program to solve a maze using a depth-first search (DFS) algorithm. This is one of the most effective and commonly used methods for exploring mazes, as it explores all possible paths before backtracking to find the solution.

Objective

The objective of this project is to develop a program that can automatically solve a maze given its structure. The maze will be represented as a grid, and the program will identify the path from the start point to the exit point using depth-first search.

Code Implementation


# Python Maze Solver using Depth-First Search (DFS)

# Maze solver function
def solve_maze(maze, start, end):
    rows, cols = len(maze), len(maze[0])
    stack = [start]  # Initialize stack with the start position
    visited = set()  # Keep track of visited positions

    while stack:
        current = stack.pop()
        x, y = current

        if current == end:
            return True  # Path found

        if current not in visited:
            visited.add(current)

            # Explore neighbors (right, left, down, up)
            neighbors = [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
            for nx, ny in neighbors:
                if 0 <= nx < rows and 0 <= ny < cols and maze[nx][ny] == 0 and (nx, ny) not in visited:
                    stack.append((nx, ny))

    return False  # No path found


# Sample maze (0 = path, 1 = wall)
maze = [
    [0, 1, 0, 0, 0],
    [0, 1, 0, 1, 0],
    [0, 0, 0, 1, 0],
    [1, 1, 0, 1, 0],
    [0, 0, 0, 0, 0]
]

start = (0, 0)  # Starting point (top-left corner)
end = (4, 4)    # Exit point (bottom-right corner)

# Call the solver function
if solve_maze(maze, start, end):
    print("Path found!")
else:
    print("No path exists.")
        

Explanation of the Program Structure

The program is structured as follows:

  • solve_maze function: This function accepts the maze (represented as a 2D list), the start point, and the end point. It performs a depth-first search (DFS) algorithm to find a path from the start to the end.
  • Stack: A stack is used to explore the maze step by step, and we backtrack when we encounter a dead-end.
  • Visited set: This keeps track of the positions we have already visited to avoid infinite loops and redundant exploration.
  • Neighbors: The program explores all four possible neighboring directions (right, left, down, up) from the current position. Only valid, unvisited paths are added to the stack for further exploration.
  • Base Case: The program stops when the current position matches the exit point, returning True to indicate the path was found.

How to Run the Program

To run this program, you need to have Python installed on your machine. Follow these steps:

  1. Install Python from here if you haven’t already.
  2. Copy the code into a Python file, for example, maze_solver.py.
  3. Open a terminal or command prompt.
  4. Navigate to the directory where you saved the maze_solver.py file.
  5. Run the program by typing python maze_solver.py in the terminal and pressing Enter.

The program will print “Path found!” if there is a path from the start to the exit in the maze. Otherwise, it will print “No path exists.”

© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)