機器人的運動範圍

【原題】
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
【思路】
主要在於遞歸的一個過程,並判斷符合條件的case,其它的並沒有什麼好說的,關鍵是要理解這個過程。另需特別注意:每次爲了不重複計算一個單元格,需要開闢一個visited數組來保存哪些元素已經給你訪問過,哪些元素還未被訪問。

public class Solution {
    public int getSum(int num){
        int count=0;
        while(num!=0){
            count+=num%10;
            num/=10;
        }
        //System.out.println(count);
        return count;
    }
    public int movingCount(int threshold, int rows, int cols)
    {
       boolean[][] visited=new boolean[rows][cols];
        return movingCountCore(threshold,rows,cols,0,0,visited);
    }
    public int movingCountCore(int threshold, int rows, int cols,int row,int col,boolean[][] visited){
        int count=0;   
        System.out.println(row+" "+col);
        if(row>=0&&col>=0&&row<rows&&col<cols&&(getSum(row)+getSum(col))<=threshold&&!visited[row][col])
                {
                visited[row][col]=true;
                    count=1+movingCountCore(threshold,rows,cols,row-1,col,visited)+
                            movingCountCore(threshold,rows,cols,row,col-1,visited)+
                            movingCountCore(threshold,rows,cols,row+1,col,visited)+
                            movingCountCore(threshold,rows,cols,row,col+1,visited);
                }
            return count;
    }
}
發佈了56 篇原創文章 · 獲贊 103 · 訪問量 21萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章