每日OJ题_牛客_NC242 单词搜索(dfs)

目录

牛客_NC242 单词搜索(dfs)

解析代码


牛客_NC242 单词搜索(dfs)

单词搜索_牛客题霸_牛客网


解析代码

简单dfs深搜应用题,dfs深搜学习博客:

Offer必备算法31_DFS回溯剪枝_九道力扣题详解(由易到难)_力扣dfs经典题-CSDN博客

class Solution {
public:
	/**
	* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
	*
	*
	* @param board string字符串vector
	* @param word string字符串
	* @return bool布尔型
	*/
	int dx[4] = { 0, 0, -1, 1 };
	int dy[4] = { 1, -1, 0, 0 };
	bool vis[101][101];
	int m = 0, n = 0;
	bool exist(vector<string>& board, string word) {
		m = board.size(), n = board[0].size();
		if (word.size() > m * n)
			return false;;
		for (int i = 0; i < m; ++i)
		{
			for (int j = 0; j < n; ++j)
			{
				if (board[i][j] == word[0])
				{
					if (dfs(board, i, j, 0, word) == true) // 从0开始写成从1开始的版本,然后几个用例没过
						return true;
				}
			}
		}
		return false;
	}
	bool dfs(vector<string>& board, int sr, int sc, int pos, string& word)
	{
		if (pos == word.size() - 1)
			return true;
		vis[sr][sc] = true;
		for (int i = 0; i < 4; ++i)
		{
			int x = sr + dx[i], y = sc + dy[i];
			if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && word[pos + 1] == board[x][y]) // pos少+1了
			{
				// if(pos == word.size())
				// return true;
				// return dfs(board, x, y, pos + 1, word);
                // 这两行写成上一行了
                if(dfs(board, x, y, pos + 1, word))
                    return true;
			}
		}
        vis[sr][sc] = false; // 恢复现场!!!!!!!!!!!这行没写
		return false;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

GR鲸鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值