題目描述
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。
例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8
= 19。請問該機器人能夠達到多少個格子?
分析
典型的DFS題。初始化一個布爾型二維map,從(0,0)開始,符合條件時,向下、右遞歸,並設此座標爲true且計數加1,若不符合條件結束遞歸(此路不通)。
代碼(已AC)
public class Solution {
int count=0;
public int movingCount(int threshold, int rows, int cols)
{
boolean[][] map = new boolean[rows][cols];
dfs(0,0,rows,cols,threshold,map);
return count;
}
public void dfs(int i, int j, int rows, int cols, int threshold, boolean[][] map){
if(i<0 || j<0 || i>=rows || j>=cols || map[i][j]) return; // 不符合條件,遞歸結束
if(validate(i,j,threshold)){
map[i][j]=true;
count++; // 符合條件,計數加1,向下、右遞歸
dfs(i+1, j, rows, cols, threshold, map);
dfs(i, j+1, rows, cols, threshold, map);
}
}
public boolean validate(int i, int j, int threshold){
int total = 0;
while(i!=0){
total += i%10;
i/=10;
}
while(j!=0){
total += j%10;
j/=10;
}
return total <= threshold;
}
}