Word Search


这道题我们有用到什么高深的算法,就一个深度搜索搞定,只是其中的判断条件比较多,需要仔细思考到每种情况,还要注意一个字母只能使用一次。

-变量,函数声明解释

  • tag数组:用来标示该字母是否已经使用过
  • flag:全局变量,如果标示是否已经找到匹配,如果为真立刻返回
  • dfsSearch函数:深搜函数
直接上代码
bool flag;
class Solution {
public:
    bool exist(vector<vector<char> >& board, string word) {
        flag = 0;
        if(board.size()*board[0].size() < word.length())
            return false;
        bool tag[100][100];
        int i,j;
        for(i=0;i<100;i++){
            for(j=0;j<100;j++)
                tag[i][j] = 0;
        }
        bool retval = 0;
        for(i=0;i<board.size();i++){
            for(j=0;j<board[0].size();j++){
                if(board[i][j] == word[0]){
                    tag[i][j] = 1;
                    retval = dfsSearch(board,word,i,j,1,tag);
                    tag[i][j] = 0;
                }

                if(retval)
                    return retval;
            }
        }
        return retval;
    }
    bool dfsSearch(vector<vector<char> > &board,string word,int x,int y,int pos,bool a[100][100]){
        if(flag)
            return true;
        if(pos == word.length()){
            flag = 1;
            return true;
        }   
        if(!flag && x-1 >=0 && a[x-1][y]!=1 && board[x-1][y] == word[pos]){
            a[x-1][y] = 1;
            dfsSearch(board,word,x-1,y,pos+1,a);
            a[x-1][y] = 0;
        }
        if(!flag && y+1 < board[0].size() && a[x][y+1]!=1 && board[x][y+1] == word[pos]){
            a[x][y+1] = 1;
            dfsSearch(board,word,x,y+1,pos+1,a);
            a[x][y+1] = 0;
        }
        if(!flag && x+1 < board.size() && a[x+1][y]!=1 && board[x+1][y] == word[pos]){
            a[x+1][y] = 1;
            dfsSearch(board,word,x+1,y,pos+1,a);
            a[x+1][y] = 0;
        }
        if(!flag && y-1 >= 0 && a[x][y-1]!=1 && board[x][y-1] == word[pos]){
            a[x][y-1] = 1;
            dfsSearch(board,word,x,y-1,pos+1,a);
            a[x][y-1] = 0;
        }
        return flag;
    }
};

运行时间这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值