机器人的运动范围
机器人的运动范围
https://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8?tpId=13&tqId=11219&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey
使用递归,判断所有的点机器人是否可达即可
public class Solution { public int movingCount(int threshold, int rows, int cols) { int[][] flag = new int[rows][cols]; /*记录已经走过的点*/ return helper(0,0,rows,cols,flag,threshold); } public int helper(int i, int j, int rows, int cols, int[][] flag, int threshold){ if(i < 0 || i >= rows || j < 0 || j >= cols || flag[i][j] == 1 || numSum(i)+numSum(j) > threshold) return 0; flag[i][j] = 1; return helper(i+1,j,rows,cols,flag,threshold)+helper(i-1,j,rows,cols,flag,threshold)+ helper(i,j+1,rows,cols,flag,threshold)+helper(i,j-1,rows,cols,flag,threshold)+1; } // 计算坐标的数位和 public int numSum(int num){ int sum = 0; while(num > 0){ sum += num%10; num /= 10; } return sum; } }
剑指offer 文章被收录于专栏
为刷过的每一道题都书写一篇题解,便于重复练习~