劍指offer-66題 機器人的運動範圍

題目:
地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。 例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?

思路:
此題的思路和上一道題很像,都用到了DFS,因此可以使用遞歸來實現。當機器人運動到一個可行的點後需要將計數器的值加一,之後分別在左、右、上、下進行搜索。搜索到符合條件的點則計數器(rcount)的值加一,不符合條件則返回0.

解題代碼:

public class Solution {
    /**
     * 
     * @method Desc:計算出機器人走過的格子數
     * @date 2017-10-28上午8:42:09
     */
    public int movingCount(int threshold, int rows, int cols){
        if(rows == 0 || cols == 0)
            return 0;
        //構建訪問矩陣
        boolean [][]visited = new boolean [rows][cols];
        for(int i=0;i<rows;i++){
            Arrays.fill(visited[i], false);
        }

        //計算走過的方格的個數
        return Availability(threshold, rows, cols, 0, 0, 0, visited);
    }

    //查找走過的路徑
    public int Availability(int threshold, int rows, int cols,int i,int j,int count,boolean [][]visited){
        int rcount = count;
        if(i>=rows || i<0){
            return rcount;
        }
        if(j>=cols || j<0){
            return rcount;
        }
        if(visited[i][j]){
            return rcount;
        }
        int x = i, y = j;
        //計算座標和
        int sum = 0;
        while(i != 0){
            sum += i%10;
            i/= 10;
        }
        while(j != 0){
            sum += j%10;
            j/= 10;
        }
        if(sum <= threshold){
            visited[x][y] = true;
            rcount = 1 + Availability(threshold,rows,cols,x,y+1,rcount,visited)
                       +Availability(threshold,rows,cols,x,y-1,rcount,visited)
                       +Availability(threshold,rows,cols,x+1,y,rcount,visited)
                       +Availability(threshold,rows,cols,x-1,y,rcount,visited);
        }else{
            return rcount;
        }
        return rcount;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章