刷题之单词搜索(leetcode)

很容易就想到回溯

cpp 复制代码
class Solution {
private:
    int istrue = false;
    int dir[4][2] = { -1,0,0,-1,0,1,1,0 };
    void backtracking(vector<vector<char>>& board, string word, vector<vector<bool>>& visited, int x, int y, int index)
    {
        if (index == word.size())//当找全word的字母,则标记
        {
            istrue = true;
            return;
        }
        
        for (int i = 0; i < 4; i++)
        {
            int nextx = x + dir[i][0];
            int nexty = y + dir[i][1];
            if (nextx >= board.size() || nexty >= board[0].size() || nextx < 0 || nexty < 0)
                continue;
            if (visited[nextx][nexty] == false && board[nextx][nexty] == word[index])
            {
                visited[nextx][nexty] = true;
                backtracking(board, word, visited, nextx, nexty, index + 1);
                visited[nextx][nexty] = false;//回溯
            }
        }
    }
public:
    bool exist(vector<vector<char>>& board, string word) {
        vector<vector<bool>>visited(board.size(), vector<bool>(board[0].size(), false));
        for (int i = 0; i < board.size(); i++)
        {
            for (int j = 0; j < board[0].size(); j++)
            {
                //遍历所有字母,找到word中第一个字母,再进行深度优先搜索找word的其他字母
                if (board[i][j] == word[0])
                {
                    visited[i][j] = true;
                    backtracking(board, word, visited, i, j, 1);
                    visited[i][j] = false;//回溯
                    //一旦找到,直接返回
                    if(istrue)
                        return true;
                }
            }
        }
        return istrue;
    }
};
相关推荐
2501_9249526917 分钟前
代码生成器优化策略
开发语言·c++·算法
MORE_7722 分钟前
leecode100-划分区间-贪心算法
算法·贪心算法
Book思议-39 分钟前
【数据结构实战】C语言实现栈的链式存储:从初始化到销毁,手把手教你写可运行代码
数据结构·算法·链表··408
Book思议-1 小时前
【数据结构实战】川剧 “扯脸” 与栈的 LIFO 特性 :用 C 语言实现 3 种栈结构
c语言·数据结构·算法·
3GPP仿真实验室1 小时前
【MATLAB源码】感知:CFAR 检测算法库
算法·matlab·目标跟踪
fengenrong1 小时前
20260324
c++·算法
qq_416018721 小时前
设计模式在C++中的实现
开发语言·c++·算法
倾心琴心1 小时前
【agent辅助pcb routing coding学习】实践9 CU GR 代码 算法学习
算法·agent·pcb·eda·routing
数据智能老司机1 小时前
谷歌 TurboQuant 深度拆解:LLM 内存压缩 6 倍、推理加速 8 倍、零精度损失,它是怎么做到的?
算法
2301_776508722 小时前
C++与机器学习框架
开发语言·c++·算法