【LeetCode热题100】【回溯】单词搜索

题目链接:79. 单词搜索 - 力扣(LeetCode)

要在一个二维数组里面找到一条单词路径,可以先遍历二维数组找到单词入口,然后往上下左右深度遍历,访问过的元素直接修改成字符串结束符,访问完改回去

复制代码
class Solution {
public:
    string word;
    int row, column;
    vector<vector<char> > board;

    bool dfs(int i, int j, int count) {
        if (i >= row || j >= column || i < 0 || j < 0 || board[i][j] != word[count])
            return false;
        if (count == word.size() - 1)
            return true;
        board[i][j] = '\0';
        ++count;
        bool next = dfs(i - 1, j, count) || dfs(i, j - 1, count) || dfs(i + 1, j, count) || dfs(i, j + 1, count);
        board[i][j] = word[--count];
        return next;
    }

    bool exist(vector<vector<char> > &board, string word) {
        this->board = move(board);
        this->word = move(word);
        row = this->board.size();
        column = this->board[0].size();
        for (int i = 0; i < row; ++i)
            for (int j = 0; j < column; ++j) {
                if (dfs(i, j, 0))
                    return true;
            }
        return false;
    }
};
相关推荐
骑自行车的码农14 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了15 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo15 小时前
322:零钱兑换(三种方法)
算法
NAGNIP1 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶2 天前
算法 --- 字符串
算法
博笙困了2 天前
AcWing学习——差分
c++·算法
NAGNIP2 天前
认识 Unsloth 框架:大模型高效微调的利器
算法