【劍指offer】66. 機器人的運動範圍

問題描述

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

思路

跟65很像。懶得講解了。

方法一

class Solution {
    Set<Integer> visited = new HashSet<>();
    private int rows, cols, threshold;
    int[] direcX = new int[]{-1,0,1,0};
    int[] direcY = new int[]{0,-1,0,1};
    public int movingCount(int threshold, int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        this.threshold = threshold;
        return DFS(0,0);
    }
    private int DFS(int row, int col){
        if(row<0||row>=rows||col<0||col>=cols||visited.contains(getIndex(row,col))) return 0;
        visited.add(getIndex(row,col));
        if(!isReach(getSum(row,col))) return 0;
        int res = 1;
        for(int step = 0; step < 4; step++){
            int curRow = row + direcX[step], curCol = col + direcY[step];
            res += DFS(curRow,curCol);
        }
        return res;
    }
    private int getSum(int a, int b){
        int sum = 0;
        while(a != 0){
            sum += a%10;
            a/=10;
        }
        while(b != 0){
            sum += b%10;
            b/=10;
        }
        return sum;
    }
    private boolean isReach(int sum){
        return sum <= threshold;
    }
    private int getIndex(int row, int col){
        return row*cols+col;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章