力扣每日一题 - 【单词搜索】

在这里插入图片描述

题目链接

视频链接

class Solution {
public:
    int op1[4] = {0, 1, 0, -1};
    int op2[4] = {1, 0, -1, 0}; 
    bool exist(vector<vector<char>>& board, string word) {
        for(int i = 0;i < board.size(); i++){
            for(int j = 0; j < board[0].size(); j++){  //枚举出发点
                if(dfs(board, word, i, j, 0)) return true;  
            }
        }
        return false;
    }

    bool dfs(vector<vector<char>>& board, string word, int x,int y, int u){
        if(board[x][y] != word[u]) return false;   //不匹配 
        if(u == word.size() - 1) return true;   //走到结尾位置,返回true
        char ch = board[x][y]; //提前记录,回溯的时候用于清空标记位
        board[x][y] = '.';     //标记位

        for(int i  = 0; i < 4; i++){
            int a = x + op1[i] , b = y + op2[i];  //枚举四种走向
            if(a >= board.size() || a < 0 || b >= board[0].size() || b < 0
            || board[a][b] == '.' ) continue;   //下一个位置不合法,就跳过
            if(dfs(board, word, a, b, u + 1)) return true;  //来到下一个位置,继续作为起点
        }
        board[x][y] = ch;  //还原现场值
        return false;	//不匹配

    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱生活,爱代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值