剑指 Offer(第2版)面试题 13:机器人的运动范围

剑指 Offer(第2版)面试题 13:机器人的运动范围

剑指 Offer(第2版)面试题 13:机器人的运动范围

题目来源:24. 机器人的运动范围

解法1:深度优先搜索

我们从 (0, 0) 点开始,每次朝上下左右四个方向扩展新的节点即可。

扩展时需要注意新的节点需要满足如下条件:

  • 之前没有遍历过,这个可以用一个 visited 数组来判断;
  • 没有走出边界;
  • 横纵坐标的各位数字之和小于 threshold。

最后答案就是所有遍历过的合法的节点个数 count。

代码:

class Solution
{
private:
	const int dx[4] = {-1, 0, 1, 0};
	const int dy[4] = {0, 1, 0, -1};

public:
	int movingCount(int threshold, int rows, int cols)
	{
		// 特判
		if (threshold < 0 || rows <= 0 || cols <= 0)
			return 0;
		vector<vector<bool>> visited(rows, vector<bool>(cols, false));
		int count = dfs(threshold, rows, cols, 0, 0, visited);
		return count;
	}
	// 辅函数 - 深度优先搜索
	int dfs(int threshold, int rows, int cols, int row, int col, vector<vector<bool>> &visited)
	{
		if (row < 0 || row >= rows || col < 0 || col >= cols)
			return 0;
		int cnt = 0;
		if (digitSum(row) + digitSum(col) <= threshold && visited[row][col] == false)
		{
			visited[row][col] = true;
			cnt++;
			for (int i = 0; i < 4; i++)
			{
				int x = row + dx[i], y = col + dy[i];
				cnt += dfs(threshold, rows, cols, x, y, visited);
			}
		}
		return cnt;
	}
	// 辅函数 - 求数 x 的数位之和
	int digitSum(int x)
	{
		int digit_sum = 0;
		while (x)
		{
			digit_sum += x % 10;
			x /= 10;
		}
		return digit_sum;
	}
};

复杂度分析:

时间复杂度:O(rows*cols)。每个节点最多只会入队一次,所以时间复杂度不会超过方格中的节点个数。最坏情况下会遍历方格中的所有点。

空间复杂度:O(rows*cols),用到了一个 visited 数组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

UestcXiye

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

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

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

打赏作者

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

抵扣说明:

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

余额充值