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

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

.......

.##....

.##....

....##.

..####.

...###.

.......

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

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

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

.......

.......

.......

.......

....#..

.......

.......

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

【输入格式】

第一行包含一个整数N。 (1 <= N <= 1000)

以下N行N列代表一张海域照片。

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

【输出格式】

一个整数表示答案。

【输入样例】

7

.......

.##....

.##....

....##.

..####.

...###.

.......

【输出样例】

1

资源约定:

峰值内存消耗(含虚拟机) < 256M

CPU消耗 < 1000msimport 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] == '#';

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值