机器人的路径
2017-12-08 本文已影响0人
哲哲哥
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
这一题和上一题是相似的 和求二叉树的深度也是相似的 我们要注意return的意义要相同。
public class Solution {
public int movingCount(int threshold, int rows, int cols) {
int flag[] = new int[rows * cols];
int arr[] = new int[rows * cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int i1=i;
int j1=j;
int sum1 = 0;
while (i1 != 0) {
sum1 += i1 % 10;
i1= i1 / 10;
}
while (j1 != 0) {
sum1 += j1 % 10;
j1 = j1 / 10;
}
arr[i * cols + j] = sum1;
}
}
return helper(arr, rows, cols, 0, 0, threshold, flag);
}
private int helper(int[] arr, int rows, int cols, int i, int j,
int threshold, int[] flag) {
int index = i * cols + j;
if (i >= rows || j >= cols || j < 0 || i < 0 || arr[index] > threshold
|| flag[index] == 1) {// 如果第一个字符都不满足就会返回
return 0;
}
flag[index] = 1;
int f = helper(arr, rows, cols, i - 1, j, threshold, flag)+
helper(arr, rows, cols, i + 1, j, threshold, flag)+
helper(arr, rows, cols, i, j - 1, threshold, flag)+
helper(arr, rows, cols, i, j + 1, threshold, flag)+1;
return f;
}
}