13、机器人的运动范围
题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
解法一:深度优先遍历(DFS)
public class Solution {
int res=0;
boolean visited[][];
public int movingCount(int threshold, int rows, int cols)
{
visited=new boolean[rows][cols];
backTrack(threshold,rows,cols,0,0);
return res;
}
public boolean checked(int row,int col,int threshold){
int total=0;
while(row!=0){
total+=row%10;
row/=10;
}
while(col!=0){
total+=col%10;
col/=10;
}
return total>threshold?true:false;
}
public void backTrack(int threshold,int rows,int cols,int row,int col){
if(col>=cols||row>=rows||visited[row][col]||checked(row,col,threshold)){
return;
}
res++;
visited[row][col]=true;
backTrack(threshold,rows,cols,row+1,col);
backTrack(threshold,rows,cols,row,col+1);
}
}
解法一:广度优先遍历(BFS)
import java.util.*;
public class Solution {
public int movingCount(int threshold, int rows, int cols)
{
boolean visited[][]=new boolean[rows][cols];
int res=0;
int []tmp;
int i,j;
Queue<int[]> queue=new LinkedList<>();
queue.offer(new int[]{0,0});
while(!queue.isEmpty()){
tmp=queue.poll();
i=tmp[0];
j=tmp[1];
if(i>=rows||j>=cols||checked(i,j,threshold)||visited[i][j]){
continue;
}
res++;
visited[i][j]=true;
queue.offer(new int[]{i,j+1});
queue.offer(new int[]{i+1,j});
}
return res;
}
public boolean checked(int row,int col,int threshold){
int total=0;
while(row!=0){
total+=row%10;
row/=10;
}
while(col!=0){
total+=col%10;
col/=10;
}
return total>threshold?true:false;
}
}