【剑指offer】51.机器人的运动范围

总目录:

算法之旅导航目录

 

1.问题描述

 地上有一个 rows 行和 cols 列的方格。坐标从 [0,0] 到 [rows-1,cols-1] 。

一个机器人从坐标 [0,0] 的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于 threshold 的格子。

例如,当 threshold 为 18 时,机器人能够进入方格   [35,37] ,因为 3+5+3+7 = 18。但是,它不能进入方格 [35,38] ,因为 3+5+3+8 = 19 。请问该机器人能够达到多少个格子?

数据范围: 0≤threshold≤15,1≤rows,cols≤100

进阶:空间复杂度 O(nm),时间复杂度 O(nm)

 

2.问题分析

 1回溯法

从起点开始搜索,可以到达的作上标记,后续不在搜索该点,在可达的点四周遍历递归搜索


3.代码实例

回溯法

 1 class Solution {
 2   public:
 3     int rowCnt, colCnt, thres;
 4     vector<vector<bool>> pathMap;//标记移动过的轨迹
 5 
 6     //获取指定数字的各位数之和
 7     int getNumValSum(int num) {
 8         int val = 0;
 9         while (num > 0) {
10             val += num % 10;
11             num = num / 10;
12         }
13 
14         return val;
15     }
16 
17     int valSum = 0;
18     void searchMap(const int curRow, const int curCol) {
19         //中止条件
20         //超界
21         if (curRow < 0 || curCol < 0 || curRow >= rowCnt || curCol >= colCnt) {
22             return;
23         }
24         //已经到达过的地方,不必再搜
25         if (pathMap[curRow][curCol]) {
26             return;
27         }
28 
29         //检查当前点是否可到达
30         valSum = getNumValSum(curRow) + getNumValSum(curCol);
31         if (valSum <= thres) {
32             pathMap[curRow][curCol] = true;
33         } else {
34             return;
35         }
36 
37         //遍历当前点的周边方向
38         searchMap(curRow - 1, curCol);
39         searchMap(curRow + 1, curCol);
40         searchMap(curRow, curCol - 1);
41         searchMap(curRow, curCol + 1);
42     }
43 
44     //程序入口
45     int movingCount(int threshold, int rows, int cols) {
46         //边缘保护
47         if (rows * cols <= 0) {
48             return 0;
49         }
50         if (threshold <= 0) {
51             return 1;
52         }
53 
54         //初始化地图
55         rowCnt = rows, colCnt = cols, thres = threshold;
56         for (int rowId = 0; rowId < rows; rowId++) {
57             pathMap.push_back(vector<bool>(cols, false));
58         }
59 
60         //从起点开始搜索
61         searchMap(0, 0);
62 
63         //清点可被到达的点
64         int accPoints = 0;
65         for (int rowId = 0; rowId < rowCnt; rowId++) {
66             for (int colId = 0; colId < colCnt; colId++) {
67                 accPoints += pathMap[rowId][colId] ? 1 : 0;
68             }
69         }
70 
71         return accPoints;
72     }
73 };

 

posted @ 2022-11-21 16:50  啊原来是这样呀  阅读(37)  评论(0)    收藏  举报