机器人的运动范围

题目

代码

public class Solution {
    public int movingCount(int threshold, int rows, int cols){
        if(threshold<=0||rows<=0||cols<=0){
            return 0;
        }
        boolean[][] visited = new boolean[rows][cols];
        int result = movingCountCore(threshold,rows,cols,0,0,visited);
        return result;
    }
    public int movingCountCore(int threshold, int rows,int cols,int row, int col,boolean[][] visited){
        int total=get(row)+get(col);
        if(row<rows&&row>=0&&col<cols&&col>=0&&!visited[row][col]&&(total<=threshold)){
            visited[row][col]=true;
            return 1+movingCountCore(threshold,rows,cols,row+1,col,visited)
                    +movingCountCore(threshold,rows,cols,row,col+1,visited)
                    +movingCountCore(threshold,rows,cols,row+1,col+1,visited)
                    +movingCountCore(threshold,rows,cols,row-1,col-1,visited);
        }
        return 0;
    }
    public int get(int n){
        int total=0;
        while (n>0){
            total+=n%10;
            n/=10;
        }
        return total;
    }
}
posted @ 2018-04-02 15:49  baixiaoshuai  阅读(138)  评论(0编辑  收藏  举报