刷题之单词搜索(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;
    }
};
相关推荐
计算机安禾17 小时前
【算法分析与设计】第20篇:图论中的NP困难问题与近似策略
大数据·人工智能·算法
Trouvaille ~17 小时前
【优选算法篇】深入浅出链表算法:交换、重排与合并的终极策略
c++·算法·链表·面试·蓝桥杯·笔试·后端开发
Z_Wonderful17 小时前
大文件上传-分片上传-秒传
算法·哈希算法
heimeiyingwang18 小时前
【架构实战】分布式ID生成方案:雪花算法与业务ID设计
分布式·算法·架构
圣保罗的大教堂18 小时前
leetcode 3121. 统计特殊字母的数量 II 中等
leetcode
圣保罗的大教堂18 小时前
leetcode 3120. 统计特殊字母的数量 I 简单
leetcode
RuiZN18 小时前
UE5 蓝图 FPS 01 Event Tick
c++·ue5
sheeta199818 小时前
LeetCode 每日一题笔记 日期:2026.05.28 题目:3093. 最长公共后缀查询
linux·笔记·leetcode
A charmer18 小时前
零基础学OC:变量与基本数据类型(C++开发者速通版)[特殊字符]
开发语言·c++·objective-c
SoftLipaRZC18 小时前
C语言字符完全指南:字符函数与字符串函数
c语言·开发语言·算法