LeetCode-79. 单词搜索

  1. 单词搜索

难度:中等

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

class Solution {
public:

    bool fun(vector<vector<char>>& board,vector<vector<bool>>& mark, int x,int y,string word,int index)
    {
        if(word.size() == index)return true;
        if(x>=board.size() || y >= board[0].size())return false;
        if(x<0 || y<0)return false;
        if(mark[x][y]==true)return false;
        if(board[x][y] != word[index])return false;
        //右
        bool is;
        mark[x][y] = true;
        if(fun(board,mark,x,y+1,word,index+1) || fun(board,mark,x+1,y,word,index+1) 
        || fun(board,mark,x,y-1,word,index+1) || fun(board,mark,x-1,y,word,index+1))
            return true;
        mark[x][y] = false;
        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
        int x = board.size();
        int y = board[0].size();
        vector<vector<bool>> v(x,vector<bool>(y));
        
        for(int i = 0;i< x;i++)
        {
            for(int j=0;j<y;j++)
            {
                if(fun(board,v,i,j,word,0))
                    return true;
            }
        }
         
        return false;
    }
};

执行结果:
通过
显示详情
添加备注

执行用时:
560 ms, 在所有 C++ 提交中击败了29.82%的用户
内存消耗:
7.8 MB, 在所有 C++ 提交中击败了38.33%的用户
通过测试用例:
82 / 82

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长不大的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值