每天一道Code 79. 单词搜索

在这里插入图片描述
代码思路

第一反应就是普通的dfs。但是可能真的是因为半年没敲代码,很久没敲dfs了,疯狂debug。最后莫名其妙发现是因为LeetCode没有给出输入函数,自己憨批把输入函数写挂了。所以一个简单bug一直在莫名其妙的地方找。吐了吐了。ヽ(#`Д´)ノ
就是需要回溯的dfs,当搜索失败时需要恢复标记的点。可以在原数组标记,也可以直接建一个标记数组。

第一遍出Bug的代码(已修正bug)

class Solution {
public:
    int dxy[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
    bool dfs(vector<vector<char> >& board,string &word,int Word_Index,int x,int y){
        if(Word_Index == word.length()-1) return true;
        board[x][y] = '.';                              //先置换掉当前字母
        for(int i = 0; i < 4; ++i){
            int dx = x+dxy[i][0],dy = y+dxy[i][1];
            if(dx >= 0 && dy >= 0 && dx < board.size() && dy < board[0].size() && board[dx][dy] == word[Word_Index+1] && dfs(board,word,Word_Index+1,dx,dy)) return true;
        }
        board[x][y] = word[Word_Index];                 //前面未匹配成功,恢复
        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
       for(int i=0; i < board.size(); ++i){
           for(int j = 0; j < board[i].size(); ++j){
               if(board[i][j] == word[0] && dfs(board,word,0,i,j)) return true; //开始dfs
           }
       } 
       return false;
    }
};

debug时全改的代码

class Solution {
public:
    int dxy[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
    bool dfs(vector<vector<char> >& board,string &word,int Word_Index,int x,int y){
        if(x < 0 || y < 0 || x >= board.size() || y>= board[0].size() || board[x][y] != word[Word_Index]) return false;
        if(Word_Index == word.length()-1) return true;
        board[x][y] = '.';                              //先置换掉当前字母
        if(dfs(board,word,Word_Index+1,x+1,y)||dfs(board,word,Word_Index+1,x-1,y)||dfs(board,word,Word_Index+1,x,y+1)||dfs(board,word,Word_Index+1,x,y-1)) return true;
        board[x][y] = word[Word_Index];                 //前面未匹配成功,恢复
        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
       for(int i=0; i < board.size(); ++i){
           for(int j = 0; j < board[i].size(); ++j){
               if(dfs(board,word,0,i,j)) return true; //开始dfs
           }
       } 
       return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值