Word Search

Medium

Given an m x n board and a word, find if the 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.

Example 1:

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

Output: true
Board for Example 1

Example 2:

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

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 200
  • 1 <= word.length <= 103
  • board and word consists only of lowercase and uppercase English letters.

Implementation

class Solution {
    
    private boolean[][] visited = null;
    
    public boolean exist(char[][] board, String word) {
        
        if(board == null || board.length == 0 || board[0].length == 0){
            return false;
        }
        int m = board.length;
        int n = board[0].length;
        this.visited = new boolean[m][n];
        
        for(int i = 0 ; i < m ; i++){
            for(int j = 0 ; j < n ; j++){
                if(board[i][j] == word.charAt(0) && canFormWord(board, i, j, m, n, word, 0)){
                    return true;
                }
            }
        }
        return false;
    }
    
    private boolean canFormWord(char[][] board, int i, int j, int m, int n, String word, int len){
        
        if(len == word.length()){
            return true;
        }
        if( i < 0 || i == m || j < 0 || j == n || visited[i][j] || board[i][j] != word.charAt(len)){
            return false;
        }
        visited[i][j] = true;
        if(canFormWord(board, i+1, j, m, n, word, len+1) || canFormWord(board, i-1, j, m, n, word, len+1) || 
            canFormWord(board, i, j+ 1, m, n, word, len+1)|| canFormWord(board, i, j-1, m, n, word, len+1)){
            return true;
        }
        visited[i][j] = false;
        return false;
    }
}

Time Complexcity: O(M*N*4L), where L is the length of the word.

Categories: 2D Array, DFS

Tagged as: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s