第九届 蓝桥 全球变暖 java B组

标题:全球变暖
你有一张某海域NxN像素的照片,"."表示海洋、"#"表示陆地,如下所示:
.......
.##....
.##....
....##.
..####.
...###.
.......
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。  
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。  
例如上图中的海域未来会变成如下样子:
.......
.......
.......
.......
....#..
.......
.......

请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。  
【输入格式】
第一行包含一个整数N。  (1 <= N <= 1000)  

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

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

  【输出格式】

一个整数表示答案。
【输入样例】

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

【输出样例】

1  

个人感觉从时间复杂度上来看我的这段代码可能不是最优的

程序运行图:


import java.util.Scanner;

public class Main {
public static char[][] assExp;
        public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in);
int N = scan.nextInt();
char[][] ass = new char[N][N];
for (int m = 0; m < N; m++) {
String str = scan1.nextLine();
ass[m] = str.toCharArray();
}
//获取一开始的岛屿数
int ini = getNum(ass);
assExp = new char[8][8];
for (int m = 0; m < 8; m++) {
for (int n = 0; n < 8; n++) {
assExp[m][n] = ass[m][n];
}
}
//实现海水淹没功能,用assExp进行判断,每一个‘#’上下左右如果有‘-’即将ass数组的该位置的‘#’变为‘-’
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (assExp[i][j] == '#' && (assExp[i - 1][j] == '-' || assExp[i + 1][j] == '-'
|| assExp[i][j - 1] == '-' || assExp[i][j + 1] == '-')) {
ass[i][j] = '-';
}
}
}
//计算沉没的岛屿数,并打印出来
System.out.print(ini - getNum(ass));
scan.close();
scan1.close();
}
//获取岛屿数
public static int getNum(char[][] ass) {
int Num = 0;
//数组赋值
assExp = new char[8][8];
for (int m = 0; m < 8; m++) {
for (int n = 0; n < 8; n++) {
assExp[m][n] = ass[m][n];
}
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (assExp[i][j] == '#') {
lost(i, j);
Num++;
}
}
}
return Num;
}
//递归,从找到的第一个‘#’开始四周查找(递归查找)并将该位置的‘#’变为‘-’
public static void lost(int x, int y) {
if (assExp[x][y] == '#') {
assExp[x][y] = '-';
}
if (assExp[x + 1][y] == '#') {
lost(x + 1, y);
}
if (x >= 0 && y > 0) {
if (assExp[x][y - 1] == '#') {
lost(x, y - 1);
}
}
if (x > 0 && y >= 0) {
if (assExp[x - 1][y] == '#') {
lost(x - 1, y);
}
}
if (assExp[x][y + 1] == '#') {
lost(x, y + 1);
}
}
}

猜你喜欢

转载自blog.csdn.net/qq_40712210/article/details/79970963