[剑指Offer] 66.机器人的运动范围

题目描述

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

【思路】DFS

 1 class Solution {
 2 public:
 3     int flag[1000][1000];
 4     int sum(int x,int y){
 5         int sum = 0;
 6         while(x > 0){
 7             sum += x % 10;
 8             x /= 10;
 9         }
10         while(y > 0){
11             sum += y % 10;
12             y /= 10;
13         }
14         return sum;
15     }
16     int dfs(int threshold, int rows, int cols, int i, int j){
17         int count = 0;
18         if(i >= 0 && i < rows && j >= 0 && j < cols && sum(i,j) <= threshold && flag[i][j] == 0){
19             flag[i][j] = 1;
20             count += dfs(threshold, rows, cols, i - 1, j)
21                      + dfs(threshold, rows, cols, i + 1, j)
22                      + dfs(threshold, rows, cols, i, j - 1)
23                      + dfs(threshold, rows, cols, i, j + 1)
24                      + 1;
25         }
26         return count;
27     }
28     int movingCount(int threshold, int rows, int cols)
29     {
30         memset(flag,0,sizeof(flag));
31         return dfs(threshold, rows, cols, 0, 0);
32     }
33 };
原文地址:https://www.cnblogs.com/lca1826/p/6718918.html