當前位置:網站首頁>【JZOF】13機器人的運動範圍

【JZOF】13機器人的運動範圍

2022-07-23 18:14:26歎了口丶氣

import java.util.*;
public class Solution {
    
    public int movingCount(int threshold, int rows, int cols)
    {
    
        int[] visited = new int[rows*cols];
        return movingHelper(threshold,rows,cols,0,0,visited);
        
    }
    
    public int movingHelper(int threshold, int rows,int cols,int row, int col, int[] visited){
    
        int count =0;
        if(canReach(threshold,rows,cols,row,col,visited)){
    
            visited[row*cols+col]=1;
            count = 1+movingHelper(threshold,rows,cols,row-1,col,visited)
                +movingHelper(threshold,rows,cols,row+1,col,visited)
                +movingHelper(threshold,rows,cols,row,col-1,visited)
                +movingHelper(threshold,rows,cols,row,col+1,visited);
        }
        return count;
    }
    
    public boolean canReach(int threshold, int rows, int cols, int row, int col, int[] visited){
    
        if(row>=0 && row<rows && col<cols && col>=0 && visited[row*cols+col]==0 && getDigitSum(row)+getDigitSum(col)<=threshold)
            return true;
        else
            return false;
    }
    
    public int getDigitSum(int num){
    
        int sum =0;
        while(num!=0){
    
            sum = sum+ (num%10);
            num = num/10;
        }
        return sum;
    }
}

版權聲明
本文為[歎了口丶氣]所創,轉載請帶上原文鏈接,感謝
https://cht.chowdera.com/2022/204/202207231555318424.html

隨機推薦