Word Search

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.

Constraints:

  • board and word consists only of lowercase and uppercase English letters.

  • 1 <= board.length <= 200

  • 1 <= board[i].length <= 200

  • 1 <= word.length <= 10^3

class Solution {
    public boolean backtrack(char[][] board, String word, boolean[][] visited, int x, int y, int index) {
        if (x >= 0 && x < board.length && y >= 0 && y < board[0].length && !visited[x][y]
                && board[x][y] == word.charAt(index)) {
            if (index == word.length() - 1)
                return true;
            visited[x][y] = true;
            boolean ans = backtrack(board, word, visited, x + 1, y, index + 1)
                    || backtrack(board, word, visited, x - 1, y, index + 1)
                    || backtrack(board, word, visited, x, y + 1, index + 1)
                    || backtrack(board, word, visited, x, y - 1, index + 1);
            visited[x][y] = false;
            return ans;
        }
        return false;

    }

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

Last updated