2014年4月20日 星期日

[LeetCode] Word Search

Problem:
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:O(m*n)
public class Solution {
    public boolean exist(char[][] board, String word) {
        if(word == null || board.length==0 || board[0].length==0)
            return false;
        for(int i=0;i<board.length;i++)
            for(int j=0;j<board[0].length;j++)
                if(dfs(i,j,board,word,0))
                    return true;
        return false;
    }
    public boolean dfs(int i, int j, char[][] board, String word, int position)
    {
        if(board[i][j]!=word.charAt(position))
            return false;
        if(position+1 ==word.length()) 
            return true;

        char temp = board[i][j];
        board[i][j] = '#';
        position += 1;
        
        if (i > 0  && dfs(i-1, j, board, word, position))
            return true;
        if (i < board.length-1 && dfs(i+1, j, board, word, position))
            return true;
        if (j > 0  && dfs(i, j-1, board, word, position))
            return true;
        if (j < board[0].length-1 && dfs(i, j+1, board, word, position))
            return true;
        board[i][j] = temp;    
        return false;
    }
}

沒有留言:

張貼留言