Skip to lesson

Backtracking on grids

When you move from 1D arrays to a 2D grid, your choices at cell (r, c) are the four neighboring cells: Up (r - 1, c), Down (r + 1, c), Left (r, c - 1), and Right (r, c + 1). Because a single path may not step on the same cell twice, you must mark (r, c) as visited on the way down—and unmark it on the way back up so other paths can still cross that cell.

Word search

In the classic Word Search problem, you are given an R × C grid of characters board and a string word.

  1. Base case (Goal): If idx == word.length(), all characters have been matched—return true.
  2. Constraint check: If r or c is out of bounds, or board[r][c] != word.charAt(idx), return false.
  3. Choose: Temporarily overwrite char saved = board[r][c]; board[r][c] = '#'; so the current path cannot step back onto (r, c).
  4. Explore: Try all 4 neighbors (r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1) for idx + 1 using short-circuit ||.
  5. Un-choose: Restore board[r][c] = saved; before returning the boolean result.

Example 1 · Word Search on a 2D Character Board

WordSearchGrid.javaJava
public class WordSearchGrid {    private static final int[] DR = {-1, 1, 0, 0};    private static final int[] DC = {0, 0, -1, 1};
    public static boolean exist(char[][] board, String word) {        int rows = board.length;        int cols = board[0].length;        for (int r = 0; r < rows; r++) {            for (int c = 0; c < cols; c++) {                if (dfs(board, r, c, word, 0)) {                    return true;                }            }        }        return false;    }
    private static boolean dfs(char[][] board, int r, int c, String word, int idx) {        if (idx == word.length()) {            return true; // Goal: matched all characters        }        if (r < 0 || r >= board.length || c < 0 || c >= board[0].length                || board[r][c] != word.charAt(idx)) {            return false;        }
        char saved = board[r][c];        board[r][c] = '#'; // 1. Choose (mark visited in-place)
        boolean found = false;        for (int d = 0; d < 4; d++) {            if (dfs(board, r + DR[d], c + DC[d], word, idx + 1)) {                found = true;                break; // Short-circuit: one valid path is enough!            }        }
        board[r][c] = saved; // 3. Un-choose (always restore board!)        return found;    }
    public static void main(String[] args) {        char[][] board = {            {'A', 'B', 'C', 'E'},            {'S', 'F', 'C', 'S'},            {'A', 'D', 'E', 'E'}        };        System.out.println("ABCCED: " + exist(board, "ABCCED"));        System.out.println("SEE:    " + exist(board, "SEE"));        System.out.println("ABCB:   " + exist(board, "ABCB"));    }}
Output
ABCCED: true
SEE:    true
ABCB:   false

What this code does

  • "ABCB" returns false because after stepping (0,0) 'A' -> (0,1) 'B' -> (0,2) 'C', cell (0,1) holds '#', so the search cannot step back onto the same 'B'.
  • Because board[r][c] = saved runs whether found is true or false, the board is completely intact after exist(...) finishes, allowing us to call exist three times on the same board.

You want to know whether word can be traced by starting at some cell and moving horizontally or vertically to adjacent cells, without using the same cell more than once in the word. Notice that this is an existence question (boolean): as soon as one path matches every character of word (idx == word.length()), we can immediately return true all the way out! From each starting cell (r, c), dfs(board, r, c, word, idx) checks bounds and character match first:

Rat in a maze

In Rat in a Maze, a rat starts at (0, 0) of an N × N grid (open cells 1, walls 0) and lists all simple paths to (N - 1, N - 1) as strings such as "DDRDRR".

Example 2 · Rat in a Maze: Listing All Paths in Alphabetical Order

RatInAMaze.javaJava
import java.util.ArrayList;import java.util.List;
public class RatInAMaze {    // Alphabetical order of moves: Down, Left, Right, Up    private static final int[] DR = {1, 0, 0, -1};    private static final int[] DC = {0, -1, 1, 0};    private static final char[] MOVE = {'D', 'L', 'R', 'U'};
    public static List<String> findPaths(int[][] maze) {        List<String> results = new ArrayList<>();        int n = maze.length;        if (maze[0][0] == 0 || maze[n - 1][n - 1] == 0) {            return results;        }        boolean[][] visited = new boolean[n][n];        backtrack(maze, 0, 0, visited, new StringBuilder(), results);        return results;    }
    private static void backtrack(int[][] maze, int r, int c, boolean[][] visited,                                  StringBuilder path, List<String> results) {        int n = maze.length;        if (r == n - 1 && c == n - 1) {            results.add(path.toString());            return;        }        visited[r][c] = true; // Mark current cell on entry        for (int d = 0; d < 4; d++) {            int nr = r + DR[d];            int nc = c + DC[d];            if (nr >= 0 && nr < n && nc >= 0 && nc < n                    && maze[nr][nc] == 1 && !visited[nr][nc]) {                path.append(MOVE[d]);                backtrack(maze, nr, nc, visited, path, results);                path.deleteCharAt(path.length() - 1);            }        }        visited[r][c] = false; // Unmark so other paths can use (r, c)    }
    public static void main(String[] args) {        int[][] maze = {            {1, 0, 0, 0},            {1, 1, 0, 1},            {1, 1, 0, 0},            {0, 1, 1, 1}        };        System.out.println("All paths: " + findPaths(maze));    }}
Output
All paths: [DDRDRR, DRDDRR]

What this code does

  • Both paths (DDRDRR and DRDDRR) merge at cell (2, 1) and travel (2,1) -> (3,1) -> (3,2) -> (3,3).
  • If visited[r][c] = false were omitted, the first path DDRDRR would leave (2,1), (3,1), and (3,2) marked true, blocking DRDDRR from reaching the exit!

Unlike Word Search (which stops at the first true), Rat in a Maze asks for every valid path. Why is unmarking visited cells critical here? Suppose two different paths diverge at (1, 1) and both eventually pass through (2, 2) on their way to the exit. If the first path leaves (2, 2) marked as visited permanently (as standard BFS or graph DFS does), the second path will falsely think (2, 2) is a wall and miss valid answers! Exploring directions in alphabetical order 'D', 'L', 'R', 'U' automatically produces the output list in alphabetical order.

Here is the golden distinction between plain graph DFS and grid backtracking: plain DFS checks reachability ("Can I reach the exit?") and marks visited[r][c] = true permanently in O(R · C) time. Grid backtracking searches for all paths or a path with a specific sequence/length and unmarks visited[r][c] = false on return.

Marking and unmarking visited cells

You have two clean ways to mark (r, c) as visited during grid backtracking.

Example 3 · Unique Paths III: Visiting Every Non-Obstacle Square Exactly Once

UniquePathsEveryCell.javaJava
public class UniquePathsEveryCell {    private static final int[] DR = {-1, 1, 0, 0};    private static final int[] DC = {0, 0, -1, 1};
    public static int uniquePathsIII(int[][] grid) {        int startR = 0, startC = 0, walkable = 0;        for (int r = 0; r < grid.length; r++) {            for (int c = 0; c < grid[0].length; c++) {                if (grid[r][c] != -1) walkable++;                if (grid[r][c] == 1) {                    startR = r;                    startC = c;                }            }        }        return dfs(grid, startR, startC, walkable);    }
    private static int dfs(int[][] grid, int r, int c, int remaining) {        if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] == -1) {            return 0;        }        if (grid[r][c] == 2) {            return remaining == 1 ? 1 : 0; // Valid only if every walkable cell was visited!        }
        int saved = grid[r][c];        grid[r][c] = -1; // Mark visited as obstacle        int paths = 0;        for (int d = 0; d < 4; d++) {            paths += dfs(grid, r + DR[d], c + DC[d], remaining - 1);        }        grid[r][c] = saved; // Unmark        return paths;    }
    public static void main(String[] args) {        int[][] grid = {            {1, 0, 0, 0},            {0, 0, 0, 0},            {0, 0, 2, -1}        };        System.out.println("Hamiltonian paths from 1 to 2: " + uniquePathsIII(grid));    }}
Output
Hamiltonian paths from 1 to 2: 2

What this code does

  • Here 1 is the start square, 2 is the end square, 0 is an empty square, and -1 is an obstacle.
  • By counting walkable squares upfront and decrementing remaining at each step, we check remaining == 1 when landing on 2 to ensure every non-obstacle square was visited.

In detail:

  • Direction arrays: Store int[] dr = {1, 0, 0, -1} and int[] dc = {0, -1, 1, 0} (with char[] dir = {'D', 'L', 'R', 'U'}) so one 4-iteration loop replaces four copy-pasted recursive calls.
  • Never forget to restore on early return: In Word Search, capture boolean found = dfs(...) || dfs(...) || dfs(...) || dfs(...);, restore board[r][c] = saved;, and then return found;.
  1. In-place sentinel (board[r][c] = '#' or maze[r][c] = 0): Save the original value in a local variable (char saved = board[r][c]), write a sentinel character '#' that can never match a valid letter, recurse, and restore board[r][c] = saved. This uses O(1) extra heap memory beyond the recursion stack.
  2. Separate boolean[][] visited matrix: Set visited[r][c] = true before recursing and visited[r][c] = false after recursing. Use this when the input grid is read-only or when every int value is valid.

Next step

Check your understanding

10 quick questions