刷题之单词搜索(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;
    }
};
相关推荐
洛克希德马丁几秒前
QLineEdit增加点击回显功能
c++·qt·ui
Darkwanderor15 分钟前
c++STL-list的使用和迭代器
c++·list
绒绒毛毛雨30 分钟前
广告推荐算法入门 day1 --项目选型
算法·推荐算法
越城1 小时前
数据结构中的栈与队列:原理、实现与应用
c语言·数据结构·算法
似水এ᭄往昔1 小时前
【数据结构】——栈和队列OJ
c语言·数据结构·c++
wang__123001 小时前
力扣2094题解
算法·leetcode·职场和发展
GUIQU.2 小时前
【每日一题 | 2025年5.5 ~ 5.11】搜索相关题
算法·每日一题·坚持
双叶8362 小时前
(C语言)超市管理系统(测试版)(指针)(数据结构)(二进制文件读写)
c语言·开发语言·数据结构·c++
不知名小菜鸡.2 小时前
记录算法笔记(2025.5.13)二叉树的最大深度
笔记·算法
小雅痞2 小时前
[Java][Leetcode middle] 55. 跳跃游戏
java·leetcode