剑指offer之机器人的运动范围

1.题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

2.问题分析

这也是一个回溯问题,可以借鉴上一篇——矩阵中的路径。机器人可以向四周移动。

  • 机器人从(0,0)位置出发,可以向四周出发;
  • 机器人每过一个位置,就纪录下该位置,下次不能从该位置出发;
  • 每个位置需要进行边界检测。

3.源代码

int getSum(int num)
{
    if(num <= 0)
        return 0;
    int sum = 0;
    while(num)
    {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}
int movingCount(int threshold, int rows, int cols, int x, int y, vector<vector<bool>>& flag)
{
    int count = 0;
    if(x < 0 || x >=rows || y < 0 || y >= cols)
        return count;
    if(flag[x][y] == false && getSum(x) + getSum(y) <= threshold)
    {
        flag[x][y] = true;
        count = 1 + movingCount(threshold, rows, cols, x, y - 1, flag) +
                movingCount(threshold, rows, cols, x - 1, y, flag) +
                movingCount(threshold, rows, cols, x, y + 1, flag) +
                movingCount(threshold, rows, cols, x + 1, y, flag);
    }
    return count;

}
int movingCount(int threshold, int rows, int cols)
{
    vector<vector<bool>> flag(rows,vector<bool>(cols,false));
    return movingCount(threshold, rows, cols, 0, 0, flag);
}

猜你喜欢

转载自blog.csdn.net/zqw_yaomin/article/details/83188096