注:此博客不再更新,所有最新文章將發表在個人獨立博客limengting.site。分享技術,記錄生活,歡迎大家關注
題目描述
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
**思路:**回溯法,當問題看起來比較複雜的時候注意代碼模塊化
public class Solution {
public int movingCount(int threshold, int rows, int cols) {
if (threshold < 0 || rows <= 0 || cols <= 0)
return 0;
int[] flags = new int[rows * cols];
int count = movingCountCore(threshold, rows, cols, 0, 0, flags);
return count;
}
public int movingCountCore(int threshold, int rows, int cols, int row, int col, int[] flags) {
int count = 0;
if (check(threshold, rows, cols, row, col, flags)) {
flags[row * cols + col] = 1;
count = 1 + movingCountCore(threshold, rows, cols, row - 1, col, flags)
+ movingCountCore(threshold, rows, cols, row + 1, col, flags)
+ movingCountCore(threshold, rows, cols, row, col - 1, flags)
+ movingCountCore(threshold, rows, cols, row, col + 1, flags);
}
return count;
}
public boolean check(int threshold, int rows, int cols, int row, int col, int[] flags) {
if (row >= 0 && row <= rows - 1 && col >= 0 && col <= cols - 1 && flags[row * cols + col] == 0 && getDigitSum(row) + getDigitSum(col) <= threshold)
return true;
return false;
}
public int getDigitSum(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
return sum;
}
}
運行時間:12ms
佔用內存:9288k