79. Word Search

2019/10/28 Leetcode

Tags: ‘Array’, ‘Backtracking’

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Solution

Backtracking 回溯算法

public boolean exist(char[][] board, String word) {
    for (int i = 0; i < board.length; i++) {
        for (int j = 0; j < board[i].length; j ++) {
            if (backtrack(board, i, j, word, 0)) return true;
        }
    }
    return false;
}

private boolean backtrack(char[][] board, int x, int y, String word, int index) {
    if (index >= word.length()) return true; // reached end
    if (x < 0 || y < 0 || x >= board.length || y >= board[x].length) return false;
    if (board[x][y] == word.charAt(index)) {
        index++;
        char c = board[x][y];
        board[x][y] = '#'; // save and mark visited char
        
        boolean result = backtrack(board, x, y+1, word, index)
            || backtrack(board, x, y-1, word, index)
            || backtrack(board, x+1, y, word, index)
            || backtrack(board, x-1, y, word, index);
        
        board[x][y] = c; // put original character back
        return result;
    }
    return false;
}

Search

    Table of Contents