9. 全球变暖
你有一张某海域NxN像素的照片,".“表示海洋、”#"表示陆地,如下所示:
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
【输入格式】
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。
照片保证第1行、第1列、第N行、第N列的像素都是海洋。
【输出格式】
一个整数表示答案。
【输入样例】
7
…
.##…
.##…
…##.
…####.
…###.
…
【输出样例】
1
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
解析
核心考点:连通块+简单计数
对于连通块问题,通常采取DFS、BFS做,本题1 <= N <= 1000,CPU消耗 < 1000ms,使用BFS也能通过所有测试数据,这里采取BFS解答。
BFS做题逻辑:队列+自定义类
对于本题,首先定义Boolean类型的mark数组来标记访问过的"#",依次遍历整个矩阵,对于每一个连通块,统计总的陆地数量cntLand和会被淹没的陆地数量cntSwed,如果cntLand == cntSwed,那么岛屿会被淹没,计数+1。
定义自定义类Point来封装每个点:
private static class Point{
int x; //横坐标
int y; //纵坐标
Point(int x, int y){
this.x = x;
this.y = y;
}
}
队列的使用就是通用模板,详细步骤说明见代码注释:
public class _04_9全球变暖 {
private static char[][] data; //记录矩阵原始数据
private static boolean[][] mark; //标记访问过的字符
private static int[] dx = {0, 0, 1, -1};
private static int[] dy = {1, -1, 0, 0};
private static int ans = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
in.nextLine(); //吃掉换行符-因为接下来录入的是字符
data = new char[N][N];
mark = new boolean[N][N];
//录入数据
for (int i = 0; i < N; i++) {
data[i] = in.nextLine().toCharArray();
}
in.close();
//依次遍历整个矩阵
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if(!mark[i][j] && data[i][j] == '#') { //遇到连通块则对连通块进行迭代
bfs(i, j);
}
}
}
System.out.println(ans);
}
//对调用bsf的#进行连通块检查
private static void bfs(int i, int j) {
Queue<Point> queue = new LinkedList<>(); //队列通常结合对象使用
queue.offer(new Point(i, j));
mark[i][j] = true;
int cntLand = 0; //会被淹没的陆块数
int cntSwed = 0; //陆地总的陆块数
while(!queue.isEmpty()) {
cntLand++;
Point front = queue.poll(); //出队
//对front的四个方向进行判断
boolean swed = false;
for (int k = 0; k < 4; k++) {
int x = front.x + dx[k];
int y = front.y + dy[k];
if(0 <= x && x < data.length && 0 <= y
&& y < data.length && data[x][y] == '.') swed = true; //这块陆地被淹没
if(0 <= x && x < data.length
&& 0 <= y && y < data.length
&& data[x][y] == '#' && !mark[x][y]) { //是陆地并且没被访问过则入队列
mark[x][y] = true;
queue.offer(new Point(x, y));
}
}
if(swed) cntSwed++; //这块陆地有一边临海,被淹没块数+1
}
if(cntLand == cntSwed) ans++; //陆地总数和被淹没陆地总数相同
}
private static class Point{
int x; //横坐标
int y; //纵坐标
Point(int x, int y){
this.x = x;
this.y = y;
}
}
}
^ ^