Friday, October 10, 2014

[Leetcode] 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.


    bool helper(vector<vector<char> > &board, string word, int i, int j, int k)
    {
        //if all char in the word has been found in the board
        if (k == word.size())
            return true;
        //if not the correct way    
        else if (i <0 || i >= board.size() || j < 0 || j >= board[0].size() || board[i][j] == '#' || word[k] != board[i][j])
            return false;
        else 
        {
            char tmp = board[i][j];
            board[i][j] = '#';
            //if andy of all its neighbors matches, we found a solution
            if (helper(board, word, i +1, j, k+1) ||
                helper(board, word, i, j+1, k+1) ||
                helper(board, word, i-1, j, k+1) ||
                helper(board, word, i, j-1, k+1))
                return true;
            //otherwise, backtrack
            board[i][j] = tmp;
            
            return false;            
        }

    }

    bool exist(vector<vector<char> > &board, string word) {
        for(int i=0; i<board.size(); i++)
        {
            for(int j=0; j<board[0].size(); j++)
            {
                //find a char in the board match the first char of the word
                if (board[i][j] == word[0])
                {
                    if (helper(board, word, i, j, 0))
                        return true;
                }
            }
        }
        
        return false;
    }

No comments:

Post a Comment