刷题之单词搜索(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;
    }
};
相关推荐
执笔论英雄2 分钟前
【RL】Slime训练流程
算法
梭七y30 分钟前
【力扣hot100题】(103)移动零
数据结构·算法·leetcode
weixin_413063211 小时前
测试《A Simple Algorithm for Fitting a Gaussian Function》拟合
python·算法
MarkHD1 小时前
智能体在车联网中的应用:第31天 基于RLlib的多智能体PPO实战:MAPPO算法解决simple_spread合作任务
算法
IT猿手1 小时前
三维动态避障路径规划:基于部落竞争与成员合作算法(CTCM)融合动态窗口法DWA的无人机三维动态避障方法研究,MATLAB代码
算法·matlab·动态规划·无人机·路径规划·动态路径规划
T0uken1 小时前
现代 C++ 项目的 CMake 工程组织
c++
wadesir1 小时前
Java实现遗传算法(从零开始掌握智能优化算法)
java·开发语言·算法
Jeremy爱编码1 小时前
leetcode热题腐烂的橘子
算法·leetcode·职场和发展
H CHY2 小时前
C++代码
c语言·开发语言·数据结构·c++·算法·青少年编程
alphaTao2 小时前
LeetCode 每日一题 2025/12/22-2025/12/28
算法·leetcode