主体
import java.util.*;
class Main{
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
int r=scan.nextInt(),c=scan.nextInt();
int[][] grid=new int[r][c];
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
grid[i][j]=scan.nextInt();
}
}
System.out.println(helper(grid));
}
static int helper(int[][] grid){
int rows=grid.length,cols=grid[0].length;
int ans=0;
for(int r=0;r<rows;r++){
for(int c=0;c<cols;c++){
if(grid[r][c]==1){
ans++;
//抹去arr里的1
//dfs(grid,r,c);
bfs(grid,r,c);
}
}
}
return ans;
}
}
深度优先
在进入dfs前尽量剪枝,不要等进来了再剪枝,可能会栈溢出
static void dfs(int[][] grid,int r,int c){
if(r>=0 && r<grid.length && c>=0 && c<grid[0].length && grid[r][c]==1){
grid[r][c]=0;
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
int x=r+i,y=c+j;
dfs(grid,x,y);
}
}
}
}
广度优先
static class Point {
int r;
int c;
Point(int i, int j) {
r = i;
c = j;
}
}
private static void bfs(int[][] grid, int r, int c) {
Queue<Point> q=new LinkedList();
q.offer(new Point(r,c));
grid[r][c]=0;
while(!q.isEmpty()){
Point temp=q.poll();
for(int i=-1;i<=1;i++){
for(int j=-1;j<=1;j++){
int x=temp.r+i,y=temp.c+j;
if(x>=0 && x<grid.length && y>=0 && y<grid[0].length && grid[x][y]==1){
q.offer(new Point(x,y));
grid[x][y]=0;
}
}
}
}
}
日常照顾Java同学