题目:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
分析:
机器人从0,0出发,每次都要判断走的格子是否越界,或者已经走过了,或者超过了限制,如果符合条件的话,就从上下左右四个方向继续搜索即可。
程序:
C++
class Solution { public: int movingCount(int threshold, int rows, int cols) { vector<vector<int>> visit(rows, vector<int>(cols, 0)); int count = helper(threshold, 0, 0, visit); return count; } int helper(int threshold, int x, int y, vector<vector<int>> &visit){ int c = 0; if(x < 0 || x > visit.size()-1 || y < 0 || y > visit[0].size()-1 || (getSum(x)+getSum(y)) > threshold || visit[x][y] == 1){ return 0; } visit[x][y] = 1; c = 1 + helper(threshold, x+1, y, visit) + helper(threshold, x-1, y, visit) + helper(threshold, x, y+1, visit) + helper(threshold, x, y-1, visit); return c; } int getSum(int x){ int sum = 0; while(x){ sum += x % 10; x /= 10; } return sum; } };
Java
public class Solution { public int movingCount(int threshold, int rows, int cols) { int [][] visit = new int[rows][cols]; int count = helper(threshold, 0, 0, visit); return count; } public int helper(int threshold, int x, int y, int[][] visit){ int c = 0; if(x < 0 || x > visit.length-1 || y < 0 || y > visit[0].length-1 || (getSum(x)+getSum(y)) > threshold || visit[x][y] == 1){ return 0; } visit[x][y] = 1; c = 1 + helper(threshold, x+1, y, visit) + helper(threshold, x-1, y, visit) + helper(threshold, x, y+1, visit) + helper(threshold, x, y-1, visit); return c; } int getSum(int x){ int sum = 0; while(x != 0){ sum += x % 10; x /= 10; } return sum; } }