劍指Offer-其他-(10)
阿新 • • 發佈:2018-12-18
知識點:動態規劃
題目描述
地上有一個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) { int flag[][]=new int[rows][cols];//記錄是否走過,根據行數和列數初始化一個二維陣列容器。 return helper(0,0,rows,cols,flag,threshold); } //這裡自己有一次沒有寫等於,等於也是走過了呢。 private int helper(int i,int j,int rows,int cols,int flag[][],int threshold){ if(i>=rows||i<0||j>=cols||j<0||getSum(i)+getSum(j)>threshold||flag[i][j]==1)return 0; flag[i][j]=1; //回溯法,下一步,有四個方向 return helper(i-1,j,rows,cols,flag,threshold)+ helper(i+1,j,rows,cols,flag,threshold)+ helper(i,j-1,rows,cols,flag,threshold)+ helper(i,j+1,rows,cols,flag,threshold) +1; } //十位數和個位數相加的一個函式 private int getSum(int i){ int sum=0; do{ sum+=i%10;//先提取個位數 }while((i=i/10)>0); return sum; } }