剑指 Offer 13. 机器人的运动范围
题目:
思路:
和12题的回溯法类似。第一次错直接双for,对于16,8,4,直接算出25个,将10 0,……也算进去了,但是从0开始根本不能达到,所以还是要dfs。
代码:
class Solution {
public int movingCount(int m, int n, int k) {
boolean[][] valite = new boolean[m][n];
int count = dfs(0, 0, m, n, k, valite);
//这一块就O(n^2)了。在遍历的过程中直接计算count,节省了遍历的时间,直接起飞
/* for (int l = 0; l < valite.length; l++) {
for (int o = 0; o < valite[0].length; o++) {
if (valite[l][o]) {
count++;
}
}
}*/
return count;
}
private int dfs(int i, int j, int m, int n, int k, boolean[][] valite) {
if (i < 0 || i > m - 1 || j < 0 || j > n - 1 || valite[i][j] || sum(i, j) > k) {
return 0;
}
valite[i][j] = true;
return dfs(i, j + 1, m, n, k, valite) +
dfs(i, j - 1, m, n, k, valite) +
dfs(i + 1, j, m, n, k, valite) +
dfs(i - 1, j, m, n, k, valite) + 1;
}
public int sum(int a, int b) {
int sum = 0;
while (a != 0) {
sum += a % 10;
a /= 10;
}
while (b != 0) {
sum += b % 10;
b /= 10;
}
return sum;
}
}