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.

class Solution {
private:
    int m,n;
    int len;
    int dep;
    char** board;
    string word;
    int x,y;
    bool search()
    {
        if(dep==len) return true;
        int xnew[4];
        int ynew[4];
        xnew[0]=x;xnew[1]=x;xnew[2]=x-1;xnew[3]=x+1;
        ynew[0]=y-1;ynew[1]=y+1;ynew[2]=y;ynew[3]=y;
        for(int i=0;i<4;i++)
        if(xnew[i]>=0 && xnew[i]<m && ynew[i]>=0 && ynew[i]<n && board[xnew[i]][ynew[i]]==word[dep])
        {
            board[xnew[i]][ynew[i]]=0;
            dep++;
            x=xnew[i];y=ynew[i];
            if(search())return true;
            dep--;
            board[xnew[i]][ynew[i]]=word[dep];
        }
        return false;
    }
public:
    bool exist(vector<vector<char> > &board, string word) 
    {
        this->word=word;
        m=board.size();
        if(m==0return false;
        n=board[0].size();
        this->board=new char*[m];
        for(int i=0;i<m;i++)
        {
            this->board[i]=new char[n];
            for(int j=0;j<n;j++)
                this->board[i][j]=board[i][j];
        }
        
        len=word.length();
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
            if(this->board[i][j]==word[0])
            {
                this->board[i][j]=0;
                x=i;y=j;dep=1;
                if(search())    return true;
                this->board[i][j]=word[0];
            }
        return false;
    }
}; 
posted @ 2014-05-29 16:53  erictanghu  阅读(134)  评论(0编辑  收藏  举报