[LeetCode] 79. Word Search

Problem

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:

1
2
3
4
5
6
7
8
9
10
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.

Explanation

  1. First, we can iterate the board and find the character that is matched with the first character of the word. Then, think of this character as the middle, we recursivly check its top, bottom, left, right element if match with the second character of the word.

  2. Special case is we cannot use the same character twice, so we create a isUsed table that have the same size as the board. If the character is used, then we mark it as true in the isUsed table. Or if the current word match, then we mark the current word as a random character such as #, after the recursive function, we backtrack the current word to its original character.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    boolean helper(char[][] board, char[] word, int curIdx, int r, int c) {
        if (curIdx == word.length) return true;
        if (r < 0 || r >= board.length || c < 0 || c >= board[0].length) return false;
        if (board[r][c] != word[curIdx]) return false;
        char temp = board[r][c];
        board[r][c] = '#';
        boolean res = helper(board, word, curIdx+1, r-1, c)
            || helper(board, word, curIdx+1, r+1, c)
            || helper(board, word, curIdx+1, r, c+1)
            || helper(board, word, curIdx+1, r, c-1);
        board[r][c] = temp;
        return res;
    }

    public boolean exist(char[][] board, String word) {
        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board[0].length; c++) {
                if (helper(board, word.toCharArray(), 0, r, c)) return true;
            }
        }
        return false;
    }
}