面试题67:机器人的运动范围

来源:互联网 发布:兄弟连nginx视频教程 编辑:程序博客网 时间:2024/05/17 09:05
public class Solution {    public int movingCount(int threshold, int rows, int cols)    {        boolean flag[]=new boolean[rows*cols];                int count=movingCountCore(threshold,rows,cols,0,0,flag);        return count;    }        public int movingCountCore(int threshold, int rows, int cols,int row,int col,boolean[] flag){        int  count=0;        if(check(threshold,rows,cols,row,col,flag)){            flag[row*cols+col]=true;                        count=1+movingCountCore(threshold,rows,cols,row-1,col,flag)                +movingCountCore(threshold,rows,cols,row+1,col,flag)                +movingCountCore(threshold,rows,cols,row,col-1,flag)                +movingCountCore(threshold,rows,cols,row,col+1,flag);        }        return count;    }        public boolean check(int threshold,int rows,int cols,int row,int col,boolean[] flag){        if(row<rows&&row>=0&&col<cols&&col>=0&&getDig(row)+getDig(col)<=threshold&&!flag[row*cols+col]){            return true;        }        return false;    }        public int getDig(int num){        int sum=0;        while(num>0){            sum+=num%10;            num/=10;        }        return sum;    }}