机器人的活动范围

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
 1 public class Solution {
 2     public int ans;
 3     public int count(int x) {
 4         int sum = 0;
 5         while (x > 0) {
 6             sum += x % 10;
 7             x = x / 10;
 8         }
 9         
10        return sum;
11     }
12     public void dfs(int threshold, int rows, int cols, int x, int y, boolean vis[][]) {
13         int [][]shift = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
14         for (int i = 0; i < 4; ++i) {
15             int posx = x + shift[i][0];
16             int posy = y + shift[i][1];
17             if (posx >= 0 && posy >= 0 && posx < rows && posy < cols && !vis[posx][posy]) {
18                 int temp = count(posx) + count(posy);
19                 if (temp <= threshold) {
20                     vis[posx][posy] = true;
21                     ans++;
22                     dfs(threshold, rows, cols, posx, posy, vis);
23                 }
24             }
25         }
26     }
27     
28     public int movingCount(int threshold, int rows, int cols)
29     {
30         boolean [][]vis = new boolean[rows][cols];
31         vis[0][0] = true;
32         if (threshold >= 0)
33         ans = 1;
34         else 
35         ans = 0;
36         dfs(threshold, rows, cols, 0,0, vis);
37        
38         return ans;
39     }
40 }

 

posted @ 2020-02-13 20:59  hyx1  阅读(191)  评论(0编辑  收藏  举报