输入样例1:
7
.......
.##....
.##....
....##.
..####.
...###.
.......
输出样例1:
1
输入样例2:
9
.........
.##.##...
.#####...
.##.##...
.........
.##.#....
.#.###...
.#..#....
.........
输出样例2:
1
解题思路:
找被淹没的岛屿的数量,只需要找出该连通块中总有多少陆地,以及有多少陆地与海洋相邻,当二者相等时,该岛屿就会被淹没。
连通块中的陆地总数可以通过对所有进队的岛屿数量做统计;与海洋相邻的岛屿可以通过设置标志变量统计。
Java代码:
import java.io.*;
import java.util.*;
public class Main {
static int n;
static char [][]map;
static boolean [][]vis;
static int []dx = {-1, 0, 1, 0};
static int []dy = {0, 1, 0, -1};
static class Point{
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
map = new char[n][n];
vis = new boolean[n][n];
for(int i = 0; i < n; i++) {
String str = br.readLine();
for(int j = 0; j < n; j++) {
map[i][j] = str.charAt(j);
if(map[i][j] == '#') vis[i][j] = true;
}
}
bfs();
}
public static void bfs() {
int ans = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
if(vis[i][j])
if(bfs(new Point(i, j)))ans++;
System.out.println(ans);
}
public static boolean bfs(Point p) {
Queue<Point> q = new LinkedList<>();
q.add(p);
int cnt1 = 0; //连通块中总数
int cnt2 = 0; //与海相邻的个数
while(!q.isEmpty()) {
Point point = q.poll();
int x = point.x, y = point.y;
cnt1++;
vis[x][y] = false;
boolean flag = false;
for(int i = 0; i < 4; i++) {
int tx = x + dx[i], ty = y + dy[i];
if(tx < 0 || tx >= n || ty < 0 || ty >= n) continue;
if(map[tx][ty] == '.') flag = true; //表明该陆地与海相邻
if(vis[tx][ty]) {
q.add(new Point(tx, ty));
vis[tx][ty] = false;
}
}
if(flag) cnt2++;
}
if(cnt1 == cnt2) return true; //相等时,会被淹没
return false;
}
}