【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;
    }
};
相关推荐
YXXY3132 小时前
模拟算法的介绍
算法
happymaker06263 小时前
简单LRU的实现(基于LinkedHashMap)
算法·leetcode·lru
会编程的土豆3 小时前
【数据结构与算法】空间复杂度从入门到面试:不仅会算,还要会解释
数据结构·c++·算法·面试·职场和发展
普通网友3 小时前
《算法面试必刷:15 个高频 LeetCode 题(附代码)》
算法·leetcode·面试
_深海凉_3 小时前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵
张槊哲3 小时前
C++ 进阶指南:如何丝滑地理解与实践多线程与多进程
开发语言·c++·算法
代码中介商4 小时前
C语言链表完全指南:从单节点到链表管理
c语言·算法·链表
小小de风呀4 小时前
de风——【从零开始学C++】(四):类和对象(下)
开发语言·c++·算法
aqiu1111115 小时前
[特殊字符]【算法日记 14】数论入门神题:最大公约数与最小公倍数的“乘积守恒定律”
算法
保卫大狮兄5 小时前
一文讲清:仓库管理最核心的10个公式
人工智能·算法·仓库管理