【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;
    }
};
相关推荐
Nil2086 小时前
leetcode 118杨辉三角
算法·leetcode·职场和发展
wanderist.8 小时前
线性筛法详解:从筛质数到欧拉函数、Möbius 函数与约数函数
java·数据结构·算法
All for pursuit.8 小时前
【设计-1】208.实现Trie (前缀树)
数据结构·c++·算法·leetcode
weixin_307779138 小时前
C++代码实现MATLAB中的crossval函数功能
开发语言·c++·算法·matlab
青少儿编程课堂9 小时前
背包问题(0/1 背包与完全背包)解题精讲——动态规划入门
c++·python·算法·bfs·信息学竞赛
光影少年9 小时前
为什么 JavaScript 中 0.1 + 0.2 !== 0.3,如何让其相等?
前端·javascript·算法
HEJOO99 小时前
Linux 设备驱动系列——使用全局工作队列
java·linux·算法
Code_Solitude10 小时前
c语言:递归
java·c语言·算法
edtoplort10 小时前
OpenAI紧急叫停GPT-6.1 Astra训练,奥尔特曼为何踩刹车
人工智能·gpt·算法
蒜香可达鸭10 小时前
让视频生成流水线跑不崩:一个事件溯源的多 Agent 可靠执行框架
算法