-
溫馨 小提示:如果代碼看不懂,不妨拿出紙和筆,找幾個例子,多走幾遍程序,
再搜索一下相關的博客,慢慢的就加深理解了。
題目:
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
代碼思路:
回溯法:從(0,0)開始走,每成功走一步用一個flag數組標記當前位置爲1,然後從當前位置往四個方向探索,
返回1 + 4 個方向的探索值之和。
解題代碼:
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
if(threshold == 0)
return 0;
int flag[][] = new int[rows][cols];
return count(threshold, rows, cols, 0, 0, flag);
}
public int count(int threshold, int rows, int cols, int i, int j, int[][] flag){
if(i<0 || j<0 || i>=rows || j>=cols || sum(i)+sum(j) > threshold || flag[i][j] == 1){
return 0;
}
flag[i][j] = 1;
return 1 + count(threshold, rows, cols, i - 1, j, flag) +
count(threshold, rows, cols, i + 1, j, flag) +
count(threshold, rows, cols, i, j - 1, flag) +
count(threshold, rows, cols, i, j + 1, flag);
}
public int sum(int i){
int s = 0;
while(i>0){
s += i%10;
i /= 10;
}
return s;
}
}
參考文章:
https://www.weiweiblog.cn/movingcount/