机器人的运动范围
import java.util.*;
public class Solution {
public int movingCount(int threshold, int rows, int cols) {
boolean[][] visited = new boolean[rows][cols];
return test(0,0,rows,cols,threshold,visited);
}
public int test(int x,int y,int rows,int cols,int k,boolean[][]visited){
if(x<0||x>=rows||y<0||y>=cols||x%10+x/10+y%10+y/10>k||visited[x][y]){
return 0;
}
//把现在访问得到标记一下
visited[x][y]=true;
return 1+test(x+1,y,rows,cols,k,visited)+
test(x,y+1,rows,cols,k,visited)+
test(x,y+1,rows,cols,k,visited)+
test(x,y-1,rows,cols,k,visited);
}
}
计算派出机器人的数量
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param grid char字符型二维数组
* @return int整型
*/
public int numIslands (char[][] grid) {
int m=grid.length;
// write code here
int count=0;
int n=grid[0].length;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]=='1'){
dfs(grid,i,j);
count++;
}
}
}
return count;
}
public void dfs(char[][]grid,int x,int y){
if(x<0||x>=grid.length||y<0||y>=grid[0].length||grid[x][y]=='0'){
return;
}
grid[x][y]='0';
dfs(grid,x+1,y);
dfs(grid,x-1,y);
dfs(grid,x,y+1);
dfs(grid,x,y-1);
}
}
岛屿数量
import java.util.*;
public class Solution {
/**
* 判断岛屿数量
* @param grid char字符型二维数组
* @return int整型
*/
public int solve (char[][] grid) {
// write code here
int m=grid.length;
int n=grid[0].length;
int count=0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(grid[i][j]=='1'){
dfs(grid,i,j);
count++;
}
}
}
return count;
}
public void dfs(char[][]grid,int x,int y){
if(x<0||x>=grid.length||y<0||y>=grid[0].length||grid[x][y]=='0'){
return;
}
grid[x][y]='0';
dfs(grid,x+1,y);
dfs(grid,x-1,y);
dfs(grid,x,y+1);
dfs(grid,x,y-1);
}
}