刷题之单词搜索(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;
    }
};
相关推荐
涛ing1 小时前
32. C 语言 安全函数( _s 尾缀)
linux·c语言·c++·vscode·算法·安全·vim
独正己身2 小时前
代码随想录day4
数据结构·c++·算法
我不是代码教父4 小时前
[原创](Modern C++)现代C++的关键性概念: 流格式化
c++·字符串格式化·流格式化·cout格式化
利刃大大5 小时前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
子燕若水5 小时前
mac 手工安装OpenSSL 3.4.0
c++
*TQK*5 小时前
ZZNUOJ(C/C++)基础练习1041——1050(详解版)
c语言·c++·编程知识点
Rachela_z5 小时前
代码随想录算法训练营第十四天| 二叉树2
数据结构·算法
细嗅蔷薇@5 小时前
迪杰斯特拉(Dijkstra)算法
数据结构·算法
追求源于热爱!5 小时前
记5(一元逻辑回归+线性分类器+多元逻辑回归
算法·机器学习·逻辑回归
ElseWhereR6 小时前
C++ 写一个简单的加减法计算器
开发语言·c++·算法