# 剑指offer（java版）面试题13：机器人的运动范围

## 题目描述

1.使用二维数组记录方格信息，true：机器人能走到；false：机器人走不到

2.从坐标[0,0]开始往下走，如果当前坐标符合要求，数组置为true，如果数组已经为true，说明已经走过，为了防止循环递归，数组为true时，返回。

3.递归调用附近四个坐标

public class Solution {
public static int movingCount(int threshold, int rows, int cols) {
boolean[][] path = new boolean[rows][cols];
movingCount(path, rows, cols, 0, 0, threshold);
int num = 0;
for (boolean[] p : path) {
for (boolean b : p) {
if (b) {
num++;
}
}
}
return num;
}

public static void movingCount(boolean[][] path, int rows, int cols, int x, int y, int result) {
if (checkPath(path, rows, cols, x, y, result)) {
path[x][y] = true;
movingCount(path, rows, cols, x - 1, y, result);
movingCount(path, rows, cols, x + 1, y, result);
movingCount(path, rows, cols, x, y - 1, result);
movingCount(path, rows, cols, x, y + 1, result);
}
}

public static boolean checkPath(boolean[][] path, int rows, int cols, int x, int y, int result) {
if (x < 0 || x >= rows || y < 0 || y >= cols) {
return false;
}
if (path[x][y]) {
return false;
}
int k = 0;
while (x != 0) {
k += x % 10;
x = x / 10;
}

while (y != 0) {
k += y % 10;
y = y / 10;
}
return k <= result;
}
}