剑指offer 机器人的运动范围

题目描述

地上有一个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 private:
 3     //计算数位和
 4     int getDigitSum(int i) {
 5         int cnt = 0;
 6         while (i > 0) {
 7             cnt += i % 10;
 8             i /= 10;
 9         }
10         return cnt;
11     }
12     int dfs(int threshold, int i, int j, int rows, int cols, bool *visited) {
13         int count = 0;
14         //只有位置符合条件(未访问,以及横纵坐标数位和)才能访问
15         if (i >= 0 && i < rows && j >= 0 && j < cols && !visited[i * cols + j] 
16                 && (getDigitSum(i) + getDigitSum(j) <= threshold)) {
17             visited[i * cols + j] = true;
18             count = 1;
19             //上下左右四个方向
20             int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, -1, 0, 1};
21             for (int index = 0; index < 4; index++) {
22                 int newx = i + dx[index], newy = j + dy[index];
23                 count += dfs(threshold, newx, newy, rows, cols, visited);
24                 } 
25         }
26         return count;
27     }
28 public:
29     int movingCount(int threshold, int rows, int cols)
30     {
31         if (threshold < 0 || rows <= 0 || cols <= 0) {
32             return 0;
33         }
34         bool *visited = new bool[rows * cols];
35         memset(visited, false, rows * cols);
36         int count = dfs(threshold, 0, 0, rows, cols, visited);
37         delete [] visited;
38         return count;
39     }
40 };
原文地址:https://www.cnblogs.com/qinduanyinghua/p/11239930.html