剑指offer-13:机器人的运动范围

地上有一个m行n列的方格。一个机器人从坐标(0,0)的格子开始移动,它每次可以向左,右,上,下移动一格子,单不能进入坐标位数之和大于k的格子,最终机器人能够到达多少个格子。

这个方格可以看成m x n的矩阵。除矩阵边界上的格子外,其它格子都有4个相邻的格子。利用回溯法,机器人从坐标(0,0)开始移动,当它进入坐标为(i,j)的格子时,通过检查坐标的位数和来判断机器人是否能够进入。如果机器人能够进入坐标为(i,j)的格子,count首先加1,再判断它能否进入四个相邻的格子(i,j-1),(i-1,j),(i,j+1),(i+1,j)。重复这个过程,直到坐标位数之和不大于k的格子被遍历完为止,最终返回count。

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
//判断一个数字位数之和
int getDigSum(int num)
{
	int sum = 0;
	while (num > 0)
	{
		sum += num % 10;
		num /= 10;
	}
	return sum;
}
//判断能否进入格子
bool check(int themax, int rows, int cols, int row, int col, bool* visit)
{
	if (row >= 0 && row < rows&&col >= 0 && col <= cols&&getDigSum(row) + getDigSum(col) <= themax&&!visit[row*cols + col])
	{
		return true;
	}
	return false;
}
int movingCount2(int themax, int rows, int cols, int row, int col,bool* visit)
{
	int count = 0;
	if (check(themax, rows, cols, row, col, visit))
	{
		visit[row*cols + col] = true;
		//遍历一个格子周围的四个格子
		count = 1 + movingCount2(themax, rows, cols, row - 1, col, visit) +
			movingCount2(themax, rows, cols, row , col-1, visit) +
			movingCount2(themax, rows, cols, row + 1, col, visit) +
			movingCount2(themax, rows, cols, row , col+1, visit);

	}
	return count;
}
int movingCount(int themax, int rows, int cols)
{
	if (themax < 0 || rows <= 0 || cols <= 0)
	{
		return 0;
	}
	bool *visit = (bool*)malloc(rows*cols*sizeof(bool));
	//数字初始化为false表明机器人为进入过这个格子
	for (int i = 0; i < rows*cols; ++i)
	{
		visit[i] = false;
	}
	int count = movingCount2(themax, rows, cols, 0, 0, visit);
	free(visit);
	return count;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值