MENU

第九届蓝桥杯 Java A—— 全球变暖

March 22, 2019 • Read: 5009 • 算法阅读设置

你有一张某海域 NxN 像素的照片,"." 表示海洋、"#" 表示陆地,如下所示:

.......
.##....
.##....
....##.
..####.
...###.
.......

其中 "上下左右" 四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有 2 座岛屿。

由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻 (上下左右四个相邻像素中有海洋),它就会被淹没。

例如上图中的海域未来会变成如下样子:

.......
.......
.......
.......
....#..
.......
.......

请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。

【输入格式】
第一行包含一个整数 N。 (1 <= N <= 1000)
以下 N 行 N 列代表一张海域照片。

照片保证第 1 行、第 1 列、第 N 行、第 N 列的像素都是海洋。

【输出格式】
一个整数表示答案。

【输入样例】
7
.......
.##....
.##....
....##.
..####.
...###.
.......

【输出样例】
1

资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU 消耗 < 1000ms

  • import java.io.BufferedInputStream;
  • import java.util.Scanner;
  • public class Main {
  • static int n, cnt, survive;
  • static char[][] map, map_copy;
  • static int[][] dr = { { 0, 1 }, { 0, -1 }, { -1, 0 }, { 1, 0 } };
  • public static void main(String[] args) {
  • Scanner cin = new Scanner(new BufferedInputStream(System.in));
  • n = cin.nextInt();
  • map = new char[n][n];
  • map_copy = new char[n][n];
  • for (int i = 0; i < n; i++) {
  • String line = cin.next();
  • for (int j = 0; j < n; j++) {
  • map[i][j] = line.charAt(j);
  • map_copy[i][j] = map[i][j];
  • }
  • }
  • // island counting
  • for (int i = 0; i < n; i++)
  • for (int j = 0; j < n; j++)
  • if (map_copy[i][j] == '#') {
  • dfs_count(i, j);
  • cnt++;
  • }
  • // survived island counting
  • for (int i = 0; i < n; i++)
  • for (int j = 0; j < n; j++)
  • if (map[i][j] == '#')
  • if (dfs(i, j))
  • survive++;
  • System.out.println(cnt - survive);
  • }
  • static boolean dfs(int x, int y) {
  • int count = 0;
  • for (int i = 0; i < 4; i++) {
  • int nx = x + dr[i][0];
  • int ny = y + dr[i][1];
  • if (check(nx, ny))
  • count++;
  • }
  • return count == 4;
  • }
  • static void dfs_count(int x, int y) {
  • map_copy[x][y] = '.';
  • for (int i = 0; i < 4; i++) {
  • int nx = x + dr[i][0];
  • int ny = y + dr[i][1];
  • if (check_count(nx, ny))
  • dfs_count(nx, ny);
  • }
  • }
  • static boolean check_count(int nx, int ny) {
  • return nx < n && ny < n && nx >= 0 && ny >= 0 && map_copy[nx][ny] == '#';
  • }
  • static boolean check(int nx, int ny) {
  • return nx < n && ny < n && nx >= 0 && ny >= 0 && map[nx][ny] == '#';
  • }
  • }
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment

已有 1 条评论
  1. 1 1

    恕我水平不够,是不是解错了