核心思路:用额外的二维数组在5的边界上打上可行的标记,限制dfs遍历的范围。
import javax.swing.text.html.CSS;
import javax.xml.crypto.Data;
import java.util.*;
public class Main {
static int[] dx={-1,1,0,0,-1,1,1,-1};
static int[] dy={0,0,-1,1,-1,1,-1,1};
static int[][] map;
static int[][] visited;
static int[][] ac;
static int m;
static int n;
static int count;
public static void dfs(int x,int y,int[][] visited,int[][] ac){
if (visited[x][y]==1||ac[x][y]==0)return;
visited[x][y]=1;
for (int i = 0; i < 8; i++) {
int nx=x+dx[i]; int ny=y+dy[i];
if (nx<0||ny<0||nx>m-1||ny>n-1){
continue;
}
dfs(nx,ny,visited,ac);
}
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
m= scanner.nextInt();
n= scanner.nextInt();
scanner.nextLine();
map=new int[m][n];
ac=new int[m][n];
visited=new int[m][n];
String[] temp=new String[m];
for (int i = 0; i < m; i++) {
temp[i]=scanner.nextLine();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j <n; j++) {
map[i][j]= temp[i].charAt(j)-'0';
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(map[i][j]);
}
System.out.println();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (map[i][j]==5){
for (int k = 0; k < 8; k++) {
int nx=i+dx[k];
int ny=j+dy[k];
if (nx<0||ny<0||nx>m-1||ny>n-1||map[nx][ny]==5){
continue;
}
ac[nx][ny]=1;
}
}
}
}
for (int i = 0; i <m; i++) {
for (int j = 0; j <n; j++) {
if (visited[i][j]==0&&ac[i][j]==1){
count++;
dfs(i,j,visited,ac);
}
}
}
System.out.println(count);
}
}