題目描述
牛客傳送門:點擊打開鏈接
public class Title67 {
int[] visited;
int row,col;
public int movingCount(int threshold, int rows, int cols)
{
if(threshold <0)
return 0;
visited = new int[rows * cols];
row = rows;col = cols;
moving(threshold,0,0);
int count =1;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(visited[i*col+j] == 1)
count++;
}
}
return count-1; // 去除0,0
}
public void moving(int threshold,int i,int j){
if(check(threshold,i,j) == false)
return ;
System.out.println(i+" "+j);
visited[i*col+j] = 1;
moving(threshold,i-1,j);
moving(threshold,i+1,j);
moving(threshold,i,j-1);
moving(threshold,i,j+1);
}
boolean check(int threshold,int i,int j){
if(i < 0 || i>= row || j<0 || j>=col || visited[i*col+j] == 1){
return false;
}
int sum = 0;
while(i >0){
sum += i%10;
i /= 10;
}
while(j >0){
sum += j%10;
j /=10;
}
if(sum > threshold)
return false;
return true;
}
public static void main(String[] args) {
Title67 clazz = new Title67();
System.out.println(clazz.movingCount(5, 10, 10));
}
}