leetocde 79. 单词搜索

单词搜索,迷宫问题中 进行了边界限制
代码如下`(下面代码测试用例都可以通过,时间上面超过了,没想明白)

class Solution {
//这个其实就是加了一些剪枝的限制,因该说更好写了

private:
    int arr[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
    bool isArea( int temp_i,int temp_j,vector<vector<char>> board)
    {
        if(temp_i>=0&&temp_i<=board.size()-1&&temp_j>=0&&temp_j<=board[0].size()-1){return true;}
        return  false;
    }
    bool _exist(vector<vector<char>>& board,string &word,vector<vector<bool>> &used,int &index,int start_i,int start_j)
    {
        if(index==word.size())//一定要注意这里。 
        {
            return board[start_i][start_j]==word[word.size()-1];
        }

        for(int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
        {
            int temp_i=start_i+arr[i][0];
            int temp_j=start_j+arr[i][1];

            //首先判断是不是在网格内,然后判断是不是未访问,然后看是不是等于下一个字母, 在网格内,没有访问,等于下一个字母,就递归
            if(isArea(temp_i,temp_j,board)&&used[temp_i][temp_j]==false&&board[temp_i][temp_j]==word[index])
            {
                cout<<word[index]<<endl;
                used[temp_i][temp_j]=true;
                index++;
                if(_exist( board,word,used,index, temp_i, temp_j)==true)
                {
                return true;
                }
                index--;
                used[temp_i][temp_j]=false;
            }
        }
        return  false;
    }



public:
    bool exist(vector<vector<char>>& board, string word)
     {
        int index=1;
        vector<vector<bool>> used(board.size(),vector<bool>(board[0].size(),false));
        for(int i=0;i<board.size();i++)
        {
            for(int j=0;j<board[0].size();j++)
            {
                if(board[i][j]==word[0])
                {
                    used[i][j]=true;
                    if(_exist( board, word, used,index, i, j)==true)
                    {
                        return true;
                    }
                     used[i][j]=false;
                }
            }
        }
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值