0079 - Word Search

0079 - Word Search

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

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

Examples

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED" Output: true

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE" Output: true

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB" Output: false

Constraints

  • m == board.length

  • n = board[i].length

  • 1 <= m, n <= 6

  • 1 <= word.length <= 15

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

Follow up: Could you use search pruning to make your solution faster with a larger board?

Java Solution (Backtracking)

class Solution {
    public boolean exist(char[][] board, String word) {
        int rows = board.length;
        int columns = board[0].length;
        
        for (int i = 0; i < rows; i++)
          for (int j = 0; j < columns; j++)
            if (this.backtrack(i, j, rows, columns, board, word, 0))
              return true;
        return false;
    }
    
    private boolean backtrack(int row, int column, int rows, int columns, char[][] board, String word, int index) {
        if(index >= word.length()) return true;
        
        if(row < 0 || row == rows || column < 0 || column == columns || board[row][column] != word.charAt(index)) return false;
        
        int[] rowDirs = {0, 1, 0, -1};
        int[] colDirs = {1, 0, -1, 0};
        boolean ret = false;
        board[row][column] = '$';
        for(int i = 0; i < rowDirs.length; i++) {
            ret = backtrack(row + rowDirs[i], column + colDirs[i],rows, columns, board, word, index + 1);
            if (ret) break;
        }
        
        board[row][column] = word.charAt(index);
        return ret;
    }
}

Last updated