Wednesday, February 12, 2014

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.
For example,
Given board =
[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

Solution:
Use DFS for each board position.


public class Solution {
    public boolean exist(char[][] board, String word) {
        int m = board.length;
        int n = board[0].length;
        
        // to avoid duplicates
        boolean[][] 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))
                    if(helper(board, word, 0, i, j, visited))
                        return true;
            }
        }
        return false;
    }
    
    public boolean helper(char[][] board, String word, int count, int i, int j, boolean[][] visited){
        if(count == word.length())
            return true;
        // out of boundary
        if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) 
            return false;
        if(visited[i][j] || board[i][j] != word.charAt(count))
            return false;
            
        visited[i][j] = true;
        
        if(helper(board, word, count+1, i-1, j, visited) || 
           helper(board, word, count+1, i+1, j, visited) ||
           helper(board, word, count+1, i, j-1, visited) ||
           helper(board, word, count+1, i, j+1, visited))
                return true;
        
        visited[i][j] = false;
        
        return false;
    }
}

No comments:

Post a Comment