Build a Maze Solver with Java

Solve mazes using DFS and BFS algorithms on a 2D grid in Java.

Introduction

30 Second Summary

Think about the last time you were stuck at a fork in the road. Do you pick one direction and go all-in, or do you check every option level by level?

In this project, you will build a terminal-based maze solver in Java that finds paths through a grid using both Depth-First Search and Breadth-First Search. You will see firsthand why each algorithm produces different results and when to reach for one over the other.

What You'll Build

You will run your maze solver, watch DFS dive deep into dead ends, then switch to BFS and see it guarantee the shortest path on the exact same maze.

By the end of this project, you'll have:

  • A maze grid printed in your terminal from a 2D array, with walls, open paths, start, and end markers you can read at a glance.
  • Two solvers on the same maze: a DFS solver using a Stack that finds a path but wanders through dead ends, and a BFS solver using a Queue that guarantees the shortest path.
  • A side-by-side comparison showing both algorithms' visited cells, so you can answer "why BFS over DFS?" from experience.
  • Secret Mission: Use a HashMap to reconstruct and display the exact shortest path, cell by cell, from start to finish.

Are there any prerequisites?

You should be comfortable writing Java code (loops, conditionals, methods, and classes). You should also have a JDK and IntelliJ IDEA already installed on your machine.

Before We Start

Before you dive in, take a moment to lock in what you are about to build and why it matters.

Set Up Your Java Project

Before you can write algorithms that solve mazes, you need a project where your code can live and run. A clean project structure in IntelliJ IDEA means you spend your time on data structures, not on fighting build errors.

In this step, you will create a new Java project and add a starter class that proves everything compiles and runs correctly.

In this step, get ready to:
  • Create a new Java project called MazeSolver in IntelliJ IDEA.
  • Write a starter MazeSolver class and run it to confirm your setup works.
Create a new project in IntelliJ IDEA
  • Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
  • Type IntelliJ IDEA and press Enter to open it.
  • Click File in the top menu bar.
  • Select New, then Project.
  • Select Java from the generators list on the left.
  • In the Name field, enter MazeSolver.
  • Make sure the JDK dropdown shows your installed JDK.
  • Click Create.

The project opens and you should see a src folder in the Project panel on the left.

Don't see the src folder?

Make sure you selected Java from the generators list, not Kotlin or another language. If the project structure looks wrong, close it and create a new project with the correct settings.

Help me set up a Java project in IntelliJ IDEA.

Create the MazeSolver class

Every Java program needs at least one class with a main method. This method is the entry point that runs when you execute the program.

  • In the Project panel, right-click the src folder.
  • Select New, then Java Class.
  • Type MazeSolver as the name and press Enter.

IntelliJ opens the new file with an empty class. Replace the entire contents of MazeSolver.java with this code:

public class MazeSolver {
    public static void main(String[] args) {
        // Print a startup message to confirm the project runs
        System.out.println("Maze Solver - Ready!");
    }
}

What does this code do?

  • public class MazeSolver defines the class that will hold all of your maze-solving logic throughout this project.
  • public static void main(String[] args) is the entry point Java calls when you run the program.
  • System.out.println prints a message to the console so you know everything is wired up correctly.
  • Save MazeSolver.java by pressing Cmd+S (macOS) or Ctrl+S (Windows).
Run the MazeSolver class

Before you run the program, what do you expect to see in the console?

  • Click the green play button (▶) in the gutter next to the main method.
  • Select Run 'MazeSolver.main()' from the popup menu.

The Run panel opens at the bottom of IntelliJ. You should see Maze Solver - Ready! printed in the console output.

Don't see the output?

  • If you see a red error, check that the class name in your code is exactly MazeSolver and matches the filename MazeSolver.java. Java is case-sensitive.
  • Make sure you saved the file before running. Unsaved changes show a dot or asterisk on the file tab.
  • If you do not see the green play button, make sure the file is inside the src folder. Files outside src are not recognized as source code.

Help me run my MazeSolver class in IntelliJ.

✔️ Awesome, I've got everything!

Great. Double check you have saved MazeSolver.java and that the output reads Maze Solver - Ready! in the Run panel.

ⓧ I'd like to double check the full code

Here is the complete MazeSolver.java file. Make sure your code matches this exactly.

public class MazeSolver {
    public static void main(String[] args) {
        System.out.println("Maze Solver - Ready!");
    }
}

Your project is ready to go. Next up, you will build the maze itself as a 2D array and see it printed as a readable grid in your terminal.

Build and Display the Maze

Your project compiles and prints to the console. Now it is time to give the solver something to work with: the maze itself.

Before you can solve a maze, you need to represent it as data. A 2D array is the most natural way to model a grid. This is the same representation you will use for dozens of interview problems involving grids, matrices, and boards.

In this step, get ready to:
  • Define a 10x10 maze as a 2D int array with walls and open paths.
  • Write a method that prints the maze as a readable grid in the terminal.
  • Run the program and see the formatted maze with start and end markers.
Define the maze as a 2D array

A maze is a grid of cells. Each cell is either an open path or a wall. A 2D int array maps perfectly to this: 0 for open, 1 for wall.

  • In MazeSolver.java, find the opening brace of the MazeSolver class.
  • Add the following code above the main method, inside the class:
// Grid dimensions
static final int ROWS = 10;
static final int COLS = 10;

// 0 = open path, 1 = wall
static int[][] maze = {
    {0, 1, 0, 0, 0, 0, 1, 0, 0, 0},
    {0, 1, 0, 1, 1, 0, 1, 0, 1, 0},
    {0, 0, 0, 1, 0, 0, 0, 0, 1, 0},
    {0, 1, 1, 1, 0, 1, 1, 0, 1, 0},
    {0, 0, 0, 0, 0, 0, 1, 0, 0, 0},
    {1, 1, 1, 1, 1, 0, 1, 1, 1, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 1, 0},
    {0, 1, 1, 1, 1, 1, 1, 0, 1, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
    {1, 1, 1, 1, 1, 1, 1, 1, 1, 0}
};

What does this code do?

  • ROWS and COLS set the grid size to 10x10. Storing them as constants means you only change one place if you resize the maze later.
  • maze is a 2D int array where each row is its own array of 10 integers. Every 0 is a path the solver can walk through. Every 1 is a wall that blocks movement.
  • The maze is designed with multiple paths from the top-left corner to the bottom-right corner. This matters because DFS and BFS will choose different routes through it.
  • Save MazeSolver.java.
  • Click the green Run button (or press Ctrl+Shift+R on macOS). You should still see Maze Solver - Ready! in the console, confirming the new array compiles without errors.

Seeing a compilation error?

  • Check that every row in the maze array ends with a comma except the last row. A missing comma between rows is the most common cause.
  • Make sure the code is inside the class braces but above the main method. If IntelliJ highlights a red underline, hover over it to see the exact error.
  • Confirm every row has exactly 10 values. If one row has 9 or 11, Java will throw an error.

Why won't my maze array compile in Java?

Write the printMaze method

A grid of 0s and 1s is hard to read. You need a method that converts each number into a visual character so the maze looks like an actual maze in your terminal.

  • Below the closing brace of the main method (but still inside the MazeSolver class), add the following method:
// Print each cell as a character based on its value
static void printMaze(int[][] maze, boolean[][] visited) {
    for (int r = 0; r < ROWS; r++) {
        for (int c = 0; c < COLS; c++) {
            if (r == 0 && c == 0) {
                System.out.print("S "); // Start marker
            } else if (r == ROWS - 1 && c == COLS - 1) {
                System.out.print("E "); // End marker
            } else if (visited != null && visited[r][c]) {
                System.out.print(". "); // Visited cell
            } else if (maze[r][c] == 1) {
                System.out.print("# "); // Wall
            } else {
                System.out.print("  "); // Open path
            }
        }
        System.out.println();
    }
}

What does this method do?

  • The nested loops walk through every cell in the grid, row by row, column by column.
  • The if-else chain picks a character for each cell: S for the start at (0,0), E for the end at (9,9), # for walls, and a blank space for open paths.
  • The visited parameter accepts a boolean[][] that you will use in later steps. When DFS or BFS marks cells as visited, this method prints them as dots (.). For now, you will pass null.
  • Save MazeSolver.java. The method is ready, and you will call it from main in the next substep.
Call printMaze and see the maze

With the data and the display method ready, the last step is to connect them in your main method.

  • In MazeSolver.java, find the main method. Locate this line inside it:
System.out.println("Maze Solver - Ready!");
  • Replace the entire contents of the main method with the following code:
// Print the ready message with extra blank line
System.out.println("Maze Solver - Ready!\n");

// Display the maze grid
System.out.println("=== The Maze ===");
printMaze(maze, null);

What changed?

  • The \n adds an extra blank line after the ready message so the maze grid prints with some breathing room.
  • printMaze(maze, null) calls your new method, passing the maze array and null for the visited parameter since no cells have been visited yet.
  • Save MazeSolver.java.

Before you run the program, what do you expect to see in the console besides the ready message?

  • Click the green Run button (or press Ctrl+Shift+R on macOS).

You should see a formatted maze grid printed in the terminal. S marks the top-left start position. E marks the bottom-right end. # symbols are walls, and blank spaces are open paths the solver can walk through.

Don't see the maze grid?

  • If you see cannot find symbol: method printMaze, make sure the printMaze method is inside the MazeSolver class braces. It should sit below the main method.
  • If the grid looks jumbled (characters are misaligned), check that every System.out.print call prints two characters (the symbol plus a space). Missing the trailing space throws off alignment.
  • If you only see Maze Solver - Ready! and nothing else, confirm your main method includes the printMaze(maze, null) call.

Why isn't my maze printing in the IntelliJ console?

✔️ Awesome, I've got everything!

Great. Double check you have saved MazeSolver.java and your maze grid prints cleanly in the console.

ⓧ I'd like to double check the full code

Your MazeSolver.java file should contain these sections in order. Scroll up and confirm each one is present:

  • ROWS and COLS constants, both set to 10.
  • The maze 2D int array with 10 rows of 10 values each (0s and 1s).
  • The main method printing Maze Solver - Ready! followed by === The Maze === and a call to printMaze(maze, null).
  • The printMaze method taking int[][] maze and boolean[][] visited as parameters, with the if-else chain printing S, E, ., #, or a space for each cell.

Your maze is on screen and ready to be solved. Next up, you will build a DFS solver that uses a Stack to find a path through this maze.

Solve with DFS Using a Stack

Your maze is on screen, but right now it just sits there. You need an algorithm that can explore the grid, navigate around walls, and find a path from start to finish.

Depth-First Search (DFS) is one of the two fundamental graph traversal algorithms that come up in coding interviews. It works by diving as deep as possible down one path before backtracking to try another. You will implement it with an explicit Stack instead of recursion, which is the exact pattern interviewers want to see.

In this step, get ready to:
  • Build a DFS solver that uses an ArrayDeque as a stack to explore the maze.
  • Run DFS on the maze and visualize which cells it visited.
  • Observe how DFS wanders through the maze instead of taking the most direct route.
Add imports and create the DFS solver

DFS uses a stack to keep track of which cells to visit next. Each iteration pops the top cell, checks if it is the exit, marks it as visited, and pushes its unvisited neighbors. Because a stack is LIFO (last in, first out), DFS always dives deeper before backtracking.

  • In MazeSolver.java, add these two import statements at the very top of the file, above the public class MazeSolver line:
import java.util.ArrayDeque;
import java.util.Deque;
  • Next, find the closing }; of the maze array. Add the following directions array and solveDFS method directly below it, before the main method:
// Direction vectors: up, down, left, right
static int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

static boolean solveDFS(int[][] maze, int startRow, int startCol,
                        int endRow, int endCol, boolean[][] visited) {
    // Use ArrayDeque as a stack (LIFO)
    Deque<int[]> stack = new ArrayDeque<>();
    stack.push(new int[]{startRow, startCol});

    while (!stack.isEmpty()) {
        int[] current = stack.pop();
        int row = current[0];
        int col = current[1];

        // Skip out-of-bounds, walls, or already-visited cells
        if (row < 0 || row >= ROWS || col < 0 || col >= COLS) continue;
        if (maze[row][col] == 1 || visited[row][col]) continue;

        visited[row][col] = true;

        // Check if we reached the end
        if (row == endRow && col == endCol) return true;

        // Push all four neighbors onto the stack
        for (int[] dir : directions) {
            stack.push(new int[]{row + dir[0], col + dir[1]});
        }
    }
    return false;
}

What does this code do?

The directions array holds the four possible moves (up, down, left, right) as row/column offsets. This avoids writing four separate neighbor-check blocks.

  • Deque<int[]> stack = new ArrayDeque<>() creates a stack using ArrayDeque. Java's legacy Stack class is discouraged because it extends the synchronized Vector class.
  • push() adds a cell to the top of the stack. pop() removes the most recently added cell. This LIFO order is what makes DFS dive deep before backtracking.
  • The method pushes neighbors first, then validates them after popping. This "push first, check later" pattern keeps the loop clean and is common in interview solutions.

Why ArrayDeque instead of the Stack class?

The official Java documentation states that "the usage of the Stack class is discouraged" because it extends Vector, a legacy synchronized class. ArrayDeque is the modern recommended replacement. Using it shows interviewers you know current Java best practices.

Call DFS and visualize the results

The solver method exists, but nothing calls it yet. You need a small helper to count how many cells DFS visited, and then update main to run the solver and display the results.

  • Add the countVisited helper method after the closing brace of solveDFS by pasting this code:
static int countVisited(boolean[][] visited) {
    int count = 0;
    for (int r = 0; r < ROWS; r++) {
        for (int c = 0; c < COLS; c++) {
            // Increment for every cell DFS touched
            if (visited[r][c]) count++;
        }
    }
    return count;
}

What does this method do?

countVisited loops through the boolean[][] visited array and counts every true cell. This number tells you how much of the maze DFS explored on its way to the exit.

  • Now update the main method. Find this existing line:
printMaze(maze, null);
  • Add the following DFS solution block directly below that line, still inside the main method:
System.out.println("\n=== DFS Solution ===");
// Create a fresh visited grid for DFS
boolean[][] dfsVisited = new boolean[ROWS][COLS];
boolean dfsFound = solveDFS(maze, 0, 0, ROWS - 1, COLS - 1, dfsVisited);
System.out.println(dfsFound ? "DFS found a path!" : "DFS found no path.");
printMaze(maze, dfsVisited);
System.out.println("DFS visited cells: " + countVisited(dfsVisited));

What does this code do?

  • boolean[][] dfsVisited = new boolean[ROWS][COLS] creates a 10x10 grid of false values. As DFS explores, it flips cells to true.
  • solveDFS(maze, 0, 0, ROWS - 1, COLS - 1, dfsVisited) runs DFS from the top-left corner (0,0) to the bottom-right corner (9,9).
  • printMaze(maze, dfsVisited) reuses your existing method. Because printMaze already handles the visited array and prints dots for visited cells, no changes to it are needed.
  • Save MazeSolver.java.

Before you run the program, think about what you expect to see. Do you think DFS will visit every open cell in the maze, or just some of them? Will it take a direct path to the exit?

  • Run MazeSolver by clicking the green play button next to the main method, or press Ctrl+Shift+R (macOS) or Shift+F10 (Windows).

You should see the original maze printed first, followed by a "=== DFS Solution ===" header, the message "DFS found a path!", and a second maze grid where visited cells are marked with dots (.). The visited cell count is printed at the bottom.

Look at those dots carefully. DFS found a path, but it explored a lot of dead ends along the way. It did not take the most direct route. This is a core limitation of DFS that becomes important in the next step.

Seeing a compilation error?

  • Check that your two import lines are at the very top of the file, above public class MazeSolver. Imports inside the class body cause a syntax error.
  • Make sure the directions array is inside the class but outside any method. It is a static field, just like maze.
  • Confirm the new code inside main is between the existing printMaze(maze, null); line and the closing } brace of main.

Help me fix a compilation error in my MazeSolver DFS code.

✔️ Awesome, I've got everything!

Great. Double check you have saved MazeSolver.java and that DFS found a path in your output.

ⓧ I'd like to double check the full code

The full file is longer than a quick glance, so scroll up through your code and confirm these pieces are present, in this order:

  • Two import lines at the top: import java.util.ArrayDeque; and import java.util.Deque;.
  • The ROWS, COLS, maze, and directions static fields (in that order).
  • The main method with both the original maze print and the new DFS solution block.
  • The printMaze method (unchanged from the previous step).
  • The solveDFS method with the Deque<int[]> stack and the while loop.
  • The countVisited helper method at the bottom.

DFS found a path through the maze, but look at all those dots. It wandered into dead ends, backtracked, and explored cells that were nowhere near the shortest route. In the next step, you will swap the stack for a queue and see how BFS guarantees the shortest path every time.

Solve with BFS Using a Queue

In the last step, you watched DFS find a path through the maze. It worked, but look at all those dots. DFS wandered down dead ends and backtracked repeatedly before stumbling onto the exit.

That wandering is the core limitation of DFS: it finds a path, not the shortest path. BFS (Breadth-First Search) fixes this by exploring all cells at distance 1 before distance 2, distance 2 before distance 3, and so on. This is the exact "why BFS over DFS?" insight that interviewers test for.

In this step, get ready to:
  • Build a BFS solver using a Queue that guarantees the shortest path.
  • Run both DFS and BFS on the same maze and compare their visited-cell patterns side by side.
Add the Queue imports

BFS uses a FIFO (First-In, First-Out) data structure instead of a LIFO stack. In Java, the Queue interface provides this behavior, and LinkedList is its most common implementation.

  • In MazeSolver.java, find the existing import lines at the top of the file:
import java.util.ArrayDeque;
import java.util.Deque;
  • Add these two new imports directly below them, so all four imports sit together:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
Write the solveBFS method

The BFS method has almost the same shape as solveDFS. The critical difference is a single data structure swap: a Queue (FIFO) replaces the Deque used as a stack (LIFO). That one change transforms how the algorithm explores the maze.

  • Add the following solveBFS method below the closing brace of solveDFS and above the countVisited method:
    static boolean solveBFS(int[][] maze, int startRow, int startCol,
                            int endRow, int endCol, boolean[][] visited) {
        // Initialize queue and mark start as visited
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{startRow, startCol});
        visited[startRow][startCol] = true;

        while (!queue.isEmpty()) {
            int[] current = queue.poll(); // Dequeue front cell (FIFO)
            int row = current[0];
            int col = current[1];

            if (row == endRow && col == endCol) return true;

            // Explore all four neighbors
            for (int[] dir : directions) {
                int newRow = row + dir[0];
                int newCol = col + dir[1];

                // Only enqueue valid, open, unvisited cells
                if (newRow >= 0 && newRow < ROWS && newCol >= 0 && newCol < COLS
                        && maze[newRow][newCol] == 0 && !visited[newRow][newCol]) {
                    visited[newRow][newCol] = true;
                    queue.add(new int[]{newRow, newCol});
                }
            }
        }
        return false;
    }

What does this code do?

  • queue.add() puts a cell at the back of the line, and queue.poll() removes from the front. This FIFO order is what makes BFS explore level by level instead of diving deep.
  • BFS marks cells as visited when they are enqueued (visited[newRow][newCol] = true before queue.add), not when they are dequeued. This prevents the same cell from being added to the queue multiple times.
  • DFS checks bounds after popping (it pushes everything, then filters). BFS checks bounds before enqueueing (it only adds valid neighbors). Both approaches work. You will see both patterns in interview problems.

Why does BFS guarantee the shortest path?

Because the queue processes cells in the order they were discovered, BFS finishes exploring every cell at distance d before it touches any cell at distance d+1. The first time BFS reaches the end, it has taken the fewest possible steps to get there.

  • Save MazeSolver.java.
  • Check that IntelliJ shows no red underlines anywhere in the file. The new method should compile cleanly.

Seeing red underlines on Queue or LinkedList?

  • Make sure you added both import java.util.Queue; and import java.util.LinkedList; at the top of the file. Missing either one causes a compile error.
  • Confirm the method signature matches exactly: static boolean solveBFS(int[][] maze, int startRow, int startCol, int endRow, int endCol, boolean[][] visited). A missing parameter or wrong return type causes errors.

Help me debug red underlines in my solveBFS method.

Call solveBFS from main and compare both results

The method exists, but nothing calls it yet. You need to add a BFS section to main that mirrors the DFS section so you can compare both algorithms on the same maze.

  • In the main method, find this line:
        System.out.println("DFS visited cells: " + countVisited(dfsVisited));
  • Add the following BFS section directly below that line:
        System.out.println("\n=== BFS Solution ===");
        boolean[][] bfsVisited = new boolean[ROWS][COLS];
        // Run BFS on the same maze
        boolean bfsFound = solveBFS(maze, 0, 0, ROWS - 1, COLS - 1, bfsVisited);
        System.out.println(bfsFound ? "BFS found a path!" : "BFS found no path.");
        printMaze(maze, bfsVisited);
        // Print count for comparison with DFS
        System.out.println("BFS visited cells: " + countVisited(bfsVisited));

What does this code do?

  • bfsVisited is a fresh boolean[][] so BFS starts from scratch on the same maze. DFS's visited array stays separate.
  • countVisited prints the total number of cells each algorithm touched. This number is the key comparison point.
  • Save MazeSolver.java.

Before you run the program, take a guess: will BFS visit more cells, fewer cells, or about the same number as DFS?

  • Click the green Run button (or press **Shift+F10**) to run MazeSolver.

You should see three sections in your console: the original maze, the DFS solution with its visited count, and the BFS solution with its visited count. Both print found a path! but look at the dot patterns and the visited-cell counts.

What should I see?

DFS's dot pattern looks scattered. It dove deep into one direction, hit dead ends, and backtracked. BFS's dot pattern looks more uniform. It expanded outward in layers from the start, reaching every cell at distance 1 before moving to distance 2.

Compare the two visited-cell counts. The numbers tell you how much work each algorithm did to find the exit. BFS explored systematically. DFS explored opportunistically.

BFS found no path?

  • Make sure you are calling solveBFS (not solveDFS) in the new BFS section of main.
  • Check that visited[startRow][startCol] = true; appears right after queue.add in your solveBFS method. Without it, the start cell can be re-enqueued.
  • Verify you are using queue.poll() (not queue.pop()). The Queue interface uses poll() to dequeue from the front.

Help me debug my BFS method that is not finding a path through the maze.

✔️ Awesome, I've got everything!

Great. Double check you have saved MazeSolver.java.

ⓧ I'd like to double check the full code

The full file is longer than a quick glance, so scroll up through your editor and confirm these pieces are present, in order:

  • Four imports at the top: ArrayDeque, Deque, LinkedList, and Queue.
  • The main method with both DFS and BFS sections, each printing visited cell counts.
  • printMaze, solveDFS, solveBFS, and countVisited methods, in that order.

You now have both fundamental graph traversal algorithms running side by side on the same maze. You can see exactly why an interviewer would ask "when would you pick BFS over DFS?" Next up, you will tackle a Secret Mission that takes BFS one step further: reconstructing the actual shortest path, cell by cell.

Secret mission

Reconstruct the Shortest Path with a HashMap

BFS told you the shortest path exists, but can you trace the exact route? Use a HashMap to track where each cell came from, then walk backward from the exit to the entrance and light up the optimal path cell by cell.

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely locally, so there are no ongoing costs. Decide whether to keep your project files, or delete them entirely.

Resources you used:

  • MazeSolver project in IntelliJ IDEA (local files only).
  • MazeSolver.java containing your DFS, BFS, and path reconstruction code.

Keep everything running

No action needed. Choose this if you want to keep experimenting with your maze solver.

  • Your MazeSolver project stays in your IntelliJ IDEA workspace.
  • Try designing new maze layouts by editing the maze array to test your solvers on different grids.
  • This is a great foundation for adding weighted graphs (Dijkstra's algorithm) or A* search as your next DSA project.

Pause - I'll come back to this later

Since everything is local, your project stays on disk with no ongoing cost. There is nothing to pause.

  • Close the MazeSolver project in IntelliJ IDEA to free up memory.
  • Your files remain on disk. Reopen the project any time from IntelliJ's welcome screen.

Delete - I don't want to use this again

Remove the project files from your machine entirely.

  • In IntelliJ IDEA, close the MazeSolver project by clicking File, then Close Project.
  • Open Finder (macOS) or File Explorer (Windows) and navigate to the folder where you created the MazeSolver project.
  • Delete the entire MazeSolver folder.
  • On the IntelliJ IDEA welcome screen, right-click the MazeSolver entry in the recent projects list and select Remove from Recent Projects to clean up the reference.

Nice Work!

Nice Work!

Nice work! You just built a terminal-based maze solver in Java that finds paths through a 2D grid using two different algorithms.

You've learned how to:

  • Built a maze as a 2D array and printed it as a readable grid, practicing the most common data representation in grid-based interview problems.
  • Implemented DFS using a Stack (ArrayDeque) and experienced its limitation firsthand: it finds a path, but not the shortest one.
  • Implemented BFS using a Queue (LinkedList) and compared it side by side with DFS on the same maze, building the intuition for why BFS guarantees the shortest path by exploring level by level.
  • Secret Mission: Used a HashMap to reconstruct and visualize the actual shortest path cell by cell, a technique used in most graph pathfinding interview questions.

Ready to quiz yourself?