标题:全球变暖
你有一张某海域NxN像素的照片,”.”表示海洋、”#”表示陆地,如下所示:
…….
.##….
.##….
….##.
..####.
…###.
…….
其中”上下左右”四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
…….
…….
…….
…….
….#..
…….
…….
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
【输入格式】
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。
照片保证第1行、第1列、第N行、第N列的像素都是海洋。
【输出格式】
一个整数表示答案。
【输入样例】
7
…….
.##….
.##….
….##.
..####.
…###.
…….
【输出样例】
1
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
当时没写出来,后来看到别人的一点思路写的,没有测试数据,也不知道会不会超时什么的
package 小岛;
import java.util.*;
public class Main {
public static String[] strArray = new String[1010];
public static char[][] ca = new char[1010][1010];
public static int n;
public static int[] dx = { -1, 1, 0, 0 };
public static int[] dy = { 0, 0, -1, 1 };
public static int[][] overWhelm = new int[1010][1010];// 判断该陆地是否会被淹没,1表示会被淹没,大于1的数表示剩下的小岛
public static int[][] v = new int[1010][1010];// 判断该陆地是否已经搜索过
public static long num = 0;// 所有小岛数
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
for (int i = 0; i < n; i++)
strArray[i] = in.next();
BFS();// 广搜
Set<Integer> set = new HashSet<>();// 存放的是未被淹没的小岛
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (overWhelm[i][j] > 1)
set.add(overWhelm[i][j]);
System.out.println(num - (long) set.size());
}
public static Queue<Node> que = new LinkedList<>();
// 表示每一块陆地
static class Node {
public int coordX;
public int coordY;
public Node(int x, int y) {
coordX = x;
coordY = y;
}
}
public static void BFS() {
for (int i = 0; i < n; i++) {
ca[i] = strArray[i].toCharArray();
}
int d_num = 2;// 用来表示不同的小岛
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (ca[i][j] == '#' && v[i][j] == 0) {
Node node = new Node(i, j);
que.add(node);
v[i][j] = 1;
while (!que.isEmpty()) {
Node tempNode = que.remove();
check(tempNode.coordX, tempNode.coordY, d_num);
for (int k = 0; k < 4; k++) {
int tempx = tempNode.coordX + dx[k];
int tempy = tempNode.coordY + dy[k];
if (tempx >= 0 && tempy >= 0 && tempx < n && tempy < n) {
if (ca[tempx][tempy] == '.') {// 上下左右存在海洋,会被淹没
continue;
}
if (ca[tempx][tempy] == '#' && v[tempx][tempy] == 0) {
que.add(new Node(tempx, tempy));
v[tempx][tempy] = 1;
}
}
}
}
num++;
d_num++;
}
}
}
}
// 判断上下左右是否有海洋
public static void check(int tempx, int tempy, int d_num) {
for (int k = 0; k < 4; k++) {
int tax = tempx + dx[k];
int tay = tempy + dy[k];
// 边界之外全是海洋
if (tax < 0 || tay < 0 || tax >= n || tay >= n) {
overWhelm[tempx][tempy] = 1;
break;
}
if (ca[tax][tay] == '.') {
overWhelm[tempx][tempy] = 1;
break;
}
overWhelm[tempx][tempy] = d_num;
}
}
}