題目描述:
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
思路:
- 從(0,0)開始走,每成功走一步,標記當前位置爲true,然後從當前位置往四個方向探索,進而判斷周圍的四個格子。
- 判斷格子是否達標的標準是:1、當前節點在矩陣內,2、當前節點未被訪問過,3、當前節點滿足限制、
代碼:
package offer01;
public class TestNo67 {
public static void main(String[] args) {
}
public int movingCount(int threshold, int rows, int cols)
{
int visited[][] = new int[rows][cols];//記錄是否已經走過
return helper(0,0,rows,cols,visited,threshold);
}
private int helper(int i,int j,int rows,int cols,int[][] visited,int threshold){
if(i <0 || i>=rows ||j<0 || j >=cols || numSum(i) + numSum(j) > threshold || visited[i][j] == 1){
return 0;
}
visited[i][j] = 1;
return helper(i-1,j,rows,cols,visited,threshold)
+helper(i+1,j,rows,cols,visited,threshold)
+helper(i,j-1,rows,cols,visited,threshold)
+helper(i,j+1,rows,cols,visited,threshold)
+1;
}
private int numSum(int number){
int sum = 0;
while (number >0){
sum += number%10;
number /= 10;
}
return sum;
}
}