刷题之单词搜索(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;
    }
};
相关推荐
ajassi20002 小时前
开源 C++ QT Widget 开发(十五)多媒体--音频播放
linux·c++·qt·开源
焦耳加热3 小时前
阿德莱德大学Nat. Commun.:盐模板策略实现废弃塑料到单原子催化剂的高值转化,推动环境与能源催化应用
人工智能·算法·机器学习·能源·材料工程
wan5555cn3 小时前
多张图片生成视频模型技术深度解析
人工智能·笔记·深度学习·算法·音视频
u6063 小时前
常用排序算法核心知识点梳理
算法·排序
鹅毛在路上了5 小时前
C++, ffmpeg, libavcodec-RTSP拉流,opencv实时预览
c++·opencv·ffmpeg
John_ToDebug5 小时前
定制 ResourceBundle 的实现与 DuiLib 思想在 Chromium 架构下的应用解析
c++·chrome·ui
蒋星熠6 小时前
Flutter跨平台工程实践与原理透视:从渲染引擎到高质产物
开发语言·python·算法·flutter·设计模式·性能优化·硬件工程
小欣加油6 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
3Cloudream6 小时前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
王璐WL6 小时前
【c++】c++第一课:命名空间
数据结构·c++·算法