第一行输入两个整数
。
接下来
行,每行
个字符,组成围墙建设图,仅含 `'*'` 与 `'0'`。
输出一个整数,表示所有安全空地格子的总数。
2 2 ** **
0
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
private static boolean[][] visit = new boolean[500][500];
private static int[][] move = new int[][] {{0, 0, 1, -1}, {1, -1, 0, 0}};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int row = in.nextInt();
int col = in.nextInt();
char[][] array = new char[row][col];
for (int i = 0; i < row; i++) {
String line = in.next();
for (int j = 0; j < col; j++) {
array[i][j] = line.charAt(j);
}
}
int total = 0;
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (!visit[i][j] && array[i][j] == '0' && i > 0 && i < row - 1 && j > 0 &&
j < col - 1) {
queue.offer(new int[] {i, j});
visit[i][j] = true;
total += getNum(array, queue, row, col);
}
}
}
System.out.print(total);
}
private static int getNum(char[][] array, Queue<int[]> queue, int row,
int col) {
int num = 1;
boolean isBlock = true;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] position = queue.poll();
int px = position[0];
int py = position[1];
for (int j = 0; j <= 3; j++) {
int newPx = px + move[0][j];
int newPy = py + move[1][j];
if ((newPx == 0 || newPx == row - 1 || newPy == 0 || newPy == col - 1) &&
array[newPx][newPy] == '0') {
isBlock = false;
continue;
}
if (newPx > 0 && newPx < row - 1 && newPy > 0 && newPy < col - 1 &&
!visit[newPx][newPy] && array[newPx][newPy] == '0') {
visit[newPx][newPy] = true;
queue.offer(new int[] {newPx, newPy});
num++;
}
}
}
}
return isBlock ? num : 0;
}
}