Rat in a maze
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Rat in a maze looks for a path from the start to the exit by trying a direction, and walking back when it hits a wall or dead end. It is the simplest form of path finding with undo. Anything that explores routes through a map or layout uses this idea.
Practical use cases
- Web app: Warehouse picking route in an admin map. An e-commerce warehouse dashboard shows a grid of shelves and aisles, some blocked. The system must prove there is a walkable path from the packing desk to a shelf. It tries one direction, backs out of dead ends, and reports a route or "unreachable" for the manager. Because dead ends are abandoned quickly, the check finishes in a fraction of a second even on a floor with thousands of squares.
- Web app: Game level validator. A browser game lets players design their own levels. Before publishing, the page runs a quick maze search to confirm the start can reach the finish, so nobody uploads an impossible level. Creators get an instant message such as "this level cannot be finished" before publishing, and players never download an unplayable level or leave angry reviews.
- System: Robot vacuums and flood fill. A robot vacuum exploring a room tries a direction, turns back at furniture, and marks where it has been. Paint tools use the same exploring idea in their "fill with colour" bucket. The same mark-visited-and-retreat habit is what stops these programs from walking in circles forever, which is the most common bug when you first write it.
The story: The Rat and the Cheese Godown
In the old grain godown behind the mohalla market, a small rat named Chintu smelled cheese from far away. The godown was a maze of sacks stacked in a 4×4 floor, with some squares blocked by heavy sacks and others free to walk on. The cheese sat in the far corner.
Chintu's rule was simple: he could only scurry down or right. He started by going down. One step, two steps... then both ahead and right were blocked by sacks. A dead end! Chintu did not panic. He stepped back to the previous square and tried right instead.
He kept a mental trail of squares, like crumbs behind him: forward when a square was open, take the crumb back when stuck. Soon he went right, right, down, down, right, and there was the cheese.
The trail he followed, DRRDDR, is what the program returns. This is backtracking in a grid: step into a free square (choose), keep exploring, and if every move fails, step back (un-choose).
How to spot this problem, and where you need it
You need to know whether, and how, you can get from one place to another through a layout with blocked spots, and you cannot tell in advance which turns lead nowhere.
Signs you need it
- The data is a grid or map with open cells and walls, and the question is "is there a path from A to B?" or "list all paths".
- Every position offers a few moves, such as up, down, left, right, and some moves lead to dead ends.
- You need to remember cells already visited, or the search walks in circles forever.
Where to use it in a project
- Checking that a floor plan, seating map or warehouse layout is connected.
- Validating user-made game levels or puzzle boards before publishing them.
The solution
Start at the entrance and mark the cell as part of your path. Try each move in a fixed order, for example down, right, up, left, but only into cells that are open and not already on your path. If a move leads to the exit, you are done. If all moves fail, unmark the cell and step back to the previous one. This is called backtracking, and it finds a path if one exists.
Payoff: Before: a person eyeballing maps and sometimes publishing broken levels. After: every level is automatically checked in milliseconds.
Explain it like I am 8
Imagine a mouse in a tiny maze. At each square it tries to go down first, then right. If both are walls, the mouse walks back one square and tries its other way. Keep doing that until it reaches the cheese or has tried everything.
How it works, step by step
- Treat the maze as a grid of 1 (open) and 0 (wall). Start at the top-left, goal at the bottom-right.
- Base case: if the rat is on the goal square, the path is complete.
- Try each allowed direction in a fixed order (here Down then Right). Skip squares outside the grid or blocked by a wall.
- Choose: add the move to the path, explore from the new square.
- Un-choose: if exploring fails, remove the move from the path and try the next direction.
- If you also allow moving up and left, mark squares as visited so the rat never walks in circles.
The code in four languages
PHP
<?php
// Find the first path from top-left to bottom-right, moving Down then Right.
function ratInMaze(array $maze): string {
$n = count($maze);
$path = '';
$go = function (int $r, int $c) use (&$go, &$path, $maze, $n): bool {
if ($r === $n - 1 && $c === $n - 1) return true; // reached the cheese
$moves = [['D', 1, 0], ['R', 0, 1]];
foreach ($moves as [$name, $dr, $dc]) {
$nr = $r + $dr;
$nc = $c + $dc;
if ($nr >= $n || $nc >= $n || $maze[$nr][$nc] === 0) continue; // wall / outside
$path .= $name; // choose
if ($go($nr, $nc)) return true; // explore
$path = substr($path, 0, -1); // un-choose
}
return false; // dead end
};
return ($maze[0][0] === 1 && $go(0, 0)) ? $path : 'NO PATH';
}
$maze = [[1, 0, 0, 0], [1, 1, 1, 0], [1, 0, 1, 1], [0, 0, 1, 1]];
echo ratInMaze($maze) . "\n";JavaScript
// Find the first path from top-left to bottom-right, moving Down then Right.
function ratInMaze(maze) {
const n = maze.length;
let path = '';
function go(r, c) {
if (r === n - 1 && c === n - 1) return true; // reached the cheese
const moves = [['D', 1, 0], ['R', 0, 1]];
for (const [name, dr, dc] of moves) {
const nr = r + dr, nc = c + dc;
if (nr >= n || nc >= n || maze[nr][nc] === 0) continue; // wall / outside
path += name; // choose
if (go(nr, nc)) return true; // explore
path = path.slice(0, -1); // un-choose
}
return false; // dead end
}
return maze[0][0] === 1 && go(0, 0) ? path : 'NO PATH';
}
const maze = [[1, 0, 0, 0], [1, 1, 1, 0], [1, 0, 1, 1], [0, 0, 1, 1]];
console.log(ratInMaze(maze));Java
public class Main {
static final String[] NAMES = {"D", "R"};
static final int[][] MOVES = {{1, 0}, {0, 1}}; // Down, then Right
// Find the first path from top-left to bottom-right, moving Down then Right.
static String ratInMaze(int[][] maze) {
StringBuilder path = new StringBuilder();
boolean found = maze[0][0] == 1 && go(maze, 0, 0, path);
return found ? path.toString() : "NO PATH";
}
static boolean go(int[][] maze, int r, int c, StringBuilder path) {
int n = maze.length;
if (r == n - 1 && c == n - 1) return true; // reached the cheese
for (int m = 0; m < MOVES.length; m++) {
int nr = r + MOVES[m][0], nc = c + MOVES[m][1];
if (nr >= n || nc >= n || maze[nr][nc] == 0) continue; // wall / outside
path.append(NAMES[m]); // choose
if (go(maze, nr, nc, path)) return true; // explore
path.deleteCharAt(path.length() - 1); // un-choose
}
return false; // dead end
}
public static void main(String[] args) {
int[][] maze = {{1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 1, 1}, {0, 0, 1, 1}};
System.out.println(ratInMaze(maze));
}
}Go
package main
import "fmt"
// ratInMaze finds the first path from top-left to bottom-right, moving Down then Right.
func ratInMaze(maze [][]int) string {
n := len(maze)
path := ""
moves := []struct {
name string
dr, dc int
}{{"D", 1, 0}, {"R", 0, 1}}
var move func(r, c int) bool
move = func(r, c int) bool {
if r == n-1 && c == n-1 { // reached the cheese
return true
}
for _, m := range moves {
nr, nc := r+m.dr, c+m.dc
if nr >= n || nc >= n || maze[nr][nc] == 0 { // wall / outside
continue
}
path += m.name // choose
if move(nr, nc) { // explore
return true
}
path = path[:len(path)-1] // un-choose
}
return false // dead end
}
if maze[0][0] == 1 && move(0, 0) {
return path
}
return "NO PATH"
}
func main() {
maze := [][]int{{1, 0, 0, 0}, {1, 1, 1, 0}, {1, 0, 1, 1}, {0, 0, 1, 1}}
fmt.Println(ratInMaze(maze))
}Time: O(2^(n+n)) · Extra space: O(n). With only Down and Right moves, the rat takes at most 2n-2 steps and has two choices each time. Walls cut most branches short. With four directions you also need a visited grid.
Watch out for
- Forgetting to check the start square itself is open (a wall at the start means no path).
- Allowing all four directions without a visited marker, which makes the rat circle forever.
- Not removing the last move from the path when backing up, so the answer contains the dead-end steps.
Quick check
- What happens when the rat has no open Down or Right move?
- It stops the whole search
- It jumps over the wall
- It backs up one step and tries another direction
- In the demo maze, which path is found first?
- RRDDRD
- DRRDDR
- DDRRDR
- DRDRDR
- If the rat may also move up and left, what must we add?
- A visited marker
- A sorted maze
- Nothing