79. Word Search

Description

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.

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

Approach

Examples

Input:

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

word = "ABCCED"

Output: true

Solutions

/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public boolean exist(char[][] board, String word) {
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(dfs(board, word, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }
    
    private boolean dfs(char[][] board, String word, int i, int j, int k) {
        if(k == word.length()) return true;
        
        if(i < 0 || j < 0 || i >= board.length || j >= board[0].length) {
            return false;
        }
        
        if(board[i][j] == word.charAt(k)) {
            char ch = board[i][j];
            board[i][j] = '#';
            if(dfs(board, word, i-1, j, k+1) ||
                 dfs(board, word, i, j+1, k+1) ||
                 dfs(board, word, i+1, j, k+1) ||
                 dfs(board, word, i, j-1, k+1)) {
                return true;
            }
            board[i][j] = ch;
        }
        
        return false;
    }
}

Follow up

Last updated

Was this helpful?