您的位置:首页 > Web前端

剑指Offer——机器人的运动范围

2017-11-03 16:29 477 查看
题目描述:

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

分析:

图的遍历。

代码:

1 class Solution {
2 public:
3     int cnt;
4     int movingCount(int threshold, int rows, int cols) {
5         bool *flag = new bool[rows * cols];
6         memset(flag, 0, sizeof(bool)*rows * cols);
7         cnt = 0;
8         moving(threshold, rows, cols, 0, 0, flag);
9         return cnt;
10     }
11     void moving(int threshold, int rows, int cols, int i, int j, bool* flag) {
12         if(i >= 0 && i < rows && j >= 0 && j < cols && getsum(i) + getsum(j) <= threshold && flag[i * cols + j] == false) {
13             flag[i * cols + j] = true;
14             cnt++;
15             moving(threshold, rows, cols, i + 1, j, flag);
16             moving(threshold, rows, cols, i - 1, j, flag);
17             moving(threshold, rows, cols, i, j - 1, flag);
18             moving(threshold, rows, cols, i, j + 1, flag);
19         }
20     }
21     int getsum(int num) {
22         int sum = 0;
23         while(num) {
24             sum += num % 10;
25             num /= 10;
26         }
27         return sum;
28     }
29 };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: