首页 > 其他 > 详细

Word Search

时间:2014-06-04 20:53:09      阅读:420      评论:0      收藏:0      [点我收藏+]

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.

bubuko.com,布布扣
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;
    }
}; 
bubuko.com,布布扣

Word Search,布布扣,bubuko.com

Word Search

原文:http://www.cnblogs.com/erictanghu/p/3759511.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!