Backtracking on grids
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
- Base case (Goal): If
idx == word.length(), all characters have been matched—returntrue. - Constraint check: If
rorcis out of bounds, orboard[r][c] != word.charAt(idx), returnfalse. - Choose: Temporarily overwrite
char saved = board[r][c]; board[r][c] = '#';so the current path cannot step back onto(r, c). - Explore: Try all 4 neighbors
(r + 1, c),(r - 1, c),(r, c + 1),(r, c - 1)foridx + 1using short-circuit||. - Un-choose: Restore
board[r][c] = saved;before returning thebooleanresult.
Example 1 · Word Search on a 2D Character Board
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")); }}ABCCED: true SEE: true ABCB: false
What this code does
"ABCB"returnsfalsebecause 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] = savedruns whetherfoundistrueorfalse, the board is completely intact afterexist(...)finishes, allowing us to callexistthree times on the sameboard.
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
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)); }}All paths: [DDRDRR, DRDDRR]
What this code does
- Both paths (
DDRDRRandDRDDRR) merge at cell(2, 1)and travel(2,1) -> (3,1) -> (3,2) -> (3,3). - If
visited[r][c] = falsewere omitted, the first pathDDRDRRwould leave(2,1),(3,1), and(3,2)markedtrue, blockingDRDDRRfrom 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.
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
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)); }}Hamiltonian paths from 1 to 2: 2
What this code does
- Here
1is the start square,2is the end square,0is an empty square, and-1is an obstacle. - By counting
walkablesquares upfront and decrementingremainingat each step, we checkremaining == 1when landing on2to ensure every non-obstacle square was visited.
In detail:
- Direction arrays: Store
int[] dr = {1, 0, 0, -1}andint[] dc = {0, -1, 1, 0}(withchar[] 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(...);, restoreboard[r][c] = saved;, and thenreturn found;.
- In-place sentinel (
board[r][c] = '#'ormaze[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 restoreboard[r][c] = saved. This uses O(1) extra heap memory beyond the recursion stack. - Separate
boolean[][] visitedmatrix: Setvisited[r][c] = truebefore recursing andvisited[r][c] = falseafter recursing. Use this when the input grid is read-only or when everyintvalue is valid.
Next step
Check your understanding
10 quick questions