Leetcode-79_Word Searchr-典型深搜题-【C++】

79. Word Search

Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word ="ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

题目大意:

给定一个二维平面和一个单词,找出该单词是否存在于网格中。
这个词可以由顺序相邻单元格的字母构成,其中“相邻”单元格是那些水平或垂直相邻的单元格。同一个字母单元格可能不会使用一次以上。

解题思路:

需要先考虑临界状态,以及结束标志,然后剩下的使用一个d[4][2]数组表示上下左右去搜索。采用深搜dfs方式。也是比较基础的一道题。
class Solution {
public:
	vector<vector<bool> > flag;
	int d[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
	int n,m;
	bool IntArry(int x,int y){
		return x>=0&&y>=0&&x<m&&y<n;
	}
	bool searchRes(vector<vector<char> >& board,string word,int index,int startx,int starty){
		int newx,newy;
		if(index==word.size()-1){
			return board[startx][starty]==word[index];
		}
		if(board[startx][starty]==word[index]){
			flag[startx][starty] = true;
			for(int i=0;i<4;i++){
				newx = startx+d[i][0];
				newy = starty+d[i][1];
				if(IntArry(newx,newy)&&!flag[newx][newy]){
					searchRes(board,word,index+1,newx,newy);
				}
			}
			flag[startx][starty] = false;
		}
		return false;
	}
	bool exist(vector<vector<char> >& board, string word) {
		n=board.size();   //行 
		m=board[0].size(); //列
	    flag = vector<vector<bool> >(n,vector<bool>(m,false));
	
		for(int i=0;i<n;i++)
			for(int j=0;j<m;j++)
				if(searchRes(board,word,0,i,j))
					return true;
		return false;		 
	}
};

结果:429ms 计算速度不够高,有待优化

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

老陈聊架构

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

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

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

打赏作者

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

抵扣说明:

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

余额充值