C/C++面试题—机器人的运动范围【回溯法应用】

题目描述

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

解题思路

同样是回溯法的应用,不过这次不是找路径,而是找机器人能到达的位置的个数。只有到到一个合法的位置count计数+1,如果发现此路不通就回溯呗,继续尝试其他路径!

解题代码

#include <iostream>
using namespace std;
/*
题目描述:

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

*/
class SolutionRobot {
public:
    int movingCount(int threshold, int rows, int cols)
    {
        if (threshold <= 0 || rows <= 0 || cols <= 0)
            return 0;
        int count = 0;
        bool *visited = new bool[rows*cols]{ false };   //访问结点标识
        Count(0, rows, 0, cols, threshold, count,visited);
        delete[] visited;
        return count;
    }
    void Count(int row, int rows, int col, int cols, int threshold,int &count,bool* visited)
    {
        if (row >= 0 && row < rows && col >= 0 && col < cols
            && getSumNum(row) + getSumNum(col) <= threshold && !visited[row*cols + col])
        {
            count += 1; //该坐标位置满足条件,能到达的格子数+1;
            visited[row*cols + col] = true;
            Count(row+1, rows, col, cols, threshold, count,visited);
            Count(row-1, rows, col, cols, threshold, count,visited);
            Count(row, rows, col+1, cols, threshold, count,visited);
            Count(row, rows, col-1, cols, threshold, count,visited);
        }
    }
    int getSumNum(int num)  //计算数字位数之和
    {
        int sum = 0;
        while (num)
        {
            sum += num % 10;
            num /= 10;
        }
        return sum;
    }
};

int main(int argc, char *argv[])
{
    SolutionRobot robot;
    /*
    1 1 1 1
    1 1 1 1
    1 1 1 1
    1 1 1 1
    */
    //边界值为6,->16
    int result = robot.movingCount(6, 4, 4);
    cout << result << endl;
    //边界值为5,[3][3] 非法,->15
    result = robot.movingCount(5, 4, 4);
    cout << result << endl;
    //边界值为4,[3][3] [3][2] [2][3]非法,->13
    result = robot.movingCount(4, 4, 4);
    cout << result << endl;
    return 0;
}

运行测试

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_29542611/article/details/80451700