79力扣:单词搜索

cpp 复制代码
class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        int key=0;
        int row=board.size();
        int col=board[0].size();
        int wSize=word.size();
        function<void(int,int,int)> dfs=[&](int m,int n,int index){
            if(key==1){return ;}
            if(board[m][n]==word[index]){
                char tmp=board[m][n];
                board[m][n]='*';
                if(index==(word.size()-1)){
                    key=1;
                }else{
                if(m-1>=0){dfs(m-1,n,index+1);}
                if(m+1<=row-1){dfs(m+1,n,index+1);}
                if(n-1>=0){dfs(m,n-1,index+1);}
                if(n+1<=col-1){dfs(m,n+1,index+1);}
                }
                board[m][n]=tmp;
            }
        };
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                if(board[i][j]==word[0]){
                    dfs(i,j,0);
                    if(key==1) return true;
                }
            }
        }
        return false;
    }
};

对于字符串中的某个字符直接用word[index]表示。

在 C++ 中,std::to_string 函数用于将各种基本类型转换为对应的 std::string 类型。其具体行为取决于参数的类型,如下所示:

  • 整数类型int, long, long long, unsigned int, 等等)将被转换为其十进制表示的字符串。
  • 浮点数类型float, double, long double)将被转换为其小数形式的字符串,通常包括小数点和指数部分。
  • 字符类型char, wchar_t, char16_t, char32_t)将被转换为长度为 1 的字符串,包含字符本身。
  • 布尔类型bool)将被转换为 "true""false" 的字符串。
相关推荐
故事和你915 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论
脱氧核糖核酸__5 小时前
LeetCode热题100——53.最大子数组和(题解+答案+要点)
数据结构·c++·算法·leetcode
脱氧核糖核酸__5 小时前
LeetCode 热题100——42.接雨水(题目+题解+答案)
数据结构·c++·算法·leetcode
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I
c++·算法·编程·贪心·csp·信奥赛·线性扫描贪心
王老师青少年编程6 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果
c++·算法·贪心算法·csp·信奥赛·线性扫描贪心·分糖果
_日拱一卒6 小时前
LeetCode:2两数相加
算法·leetcode·职场和发展
py有趣6 小时前
力扣热门100题之零钱兑换
算法·leetcode
董董灿是个攻城狮7 小时前
Opus 4.7 来了,我并不建议你升级
算法
无敌昊哥战神7 小时前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__7 小时前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode