【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;
    }
};
相关推荐
To_OC18 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
05Kevin1 天前
lk每日冒险题--数据结构6.27
算法
To_OC2 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安2 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者2 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
kisshyshy2 天前
从递归到迭代,一文吃透二叉树的核心知识与 JavaScript 实现
javascript·算法·代码规范
To_OC3 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode