Thursday, May 2, 2013

Leetcode: Word Search in C++



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:
4 direction DFS search
bool search(vector<vector<char> > &board, string word, int pos, int x, int y,vector<vector<bool> >& mark)
    {
        if(pos==word.size())
        return true;
        if(x<0||y<0||x>=board.size()||y>=board[0].size())
        return false;
        if(board[x][y]!=word[pos]||mark[x][y]==true)
        return false;
        else
        {
            mark[x][y]=true;
            return search(board, word, pos+1, x+1 , y, mark)||search(board, word, pos+1, x-1 , y, mark)||search(board, word, pos+1, x , y+1, mark)||search(board, word, pos+1, x , y-1, mark);
        }
    }
    bool exist(vector<vector<char> > &board, string word) {
        int len = word.size();
        
        int pos = 0;
        for(int i=0;i<board.size();i++)
        {
            for(int j=0;j<board[i].size();j++)
            {
                if(board[i][j] == word[pos])
                {
                    vector<vector<bool> > mark(board.size(),vector<bool>(board[0].size(),false));
                    if(search(board, word, pos, i , j, mark))
                    return true;
                }
            }
        }
        return false;
    }

No comments:

Post a Comment