题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
题意:在m x n 的矩阵中, 在限制条件 N 的情况下能到达哪些点,且记住这些点是联通的!(也就是可以连续到达的),因为需要时联通的,所以用DFS直接寻找,
两个辅助数组 vis[][] && isWall[][] 前者记录这个地方是否到达过,后者记录这个地方是否合法!
直接从(0,0)开始dfs就可以了,终止DFS的条件就是 1、越界 2、vis[][] == true 3、isWall[][]==true
public class Solution {
public int cango;
public boolean[][] vis;
public boolean[][] isWall;
public int rows;
public int cols;
public int movingCount(int threshold, int row, int col)
{
if (threshold<0||row<0||col<0){
return 0;
}
this.rows=row;
this.cols=col;
this.vis=new boolean[row][col];
this.isWall=new boolean[row][col];
for (int i = 0; i <row ; i++) {
for (int j = 0; j <col ; j++) {
vis[i][j]=false;
if (((i/10)+(i%10)+(j/10)+(j%10))>threshold){
isWall[i][j]=true;
}else {
isWall[i][j]=false;
}
}
}
DFS(0,0);
return cango;
}
private void DFS(int i, int j) {
//System.out.println("--------");
/*System.out.println(OutBound(rows,i,cols,j));
System.out.println(vis[i][j]);
System.out.println(isWall[i][j]);*/
if (OutBound(rows,i,cols,j)||vis[i][j]||isWall[i][j]){
return ;
}
//System.out.println("--------");
//visited
vis[i][j]=true;
cango++;
//DFS
DFS(i+1,j);
DFS(i-1,j);
DFS(i,j+1);
DFS(i,j-1);
}
private boolean OutBound(int rows,int row, int cols,int col) {
if (row<0||row>=rows||col<0||col>=cols){
return true;
}
return false;
}
}