码迷,mamicode.com
首页 > 其他好文 > 详细

Word Search

时间:2014-06-04 20:56:34      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

标签:c   style   class   blog   code   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!