标题:全球变暖
题目描述
你有一张某海域NxN像素的照片,"."表示海洋、"#"表示陆地,如下所示:
.......
.##....
.##....
....##.
..####.
...###.
.......
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
.......
.......
.......
.......
....#..
.......
.......
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
【输入格式】
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。
照片保证第1行、第1列、第N行、第N列的像素都是海洋。
【输出格式】
一个整数表示答案。
【输入样例】
7
.......
.##....
.##....
....##.
..####.
...###.
.......【输出样例】
1
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
解题思路
先对地图进行搜索看有多少块岛屿,第k块岛屿标注k,即如果(i,j)位置属于岛屿k,就领color[ i][ j] = k, 全部标注完后把靠近海洋的color全部变成 0,最后枚举全图,要是还有color的值为k,就说明岛屿k还存在。
最好用bfs,dfs极端数据会爆栈
没地交,代码
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;
char mp[1005][1005];
int mpp[1005][1005],n;
bool book[100001];
struct Node {
int x,y;
Node(int xx,int yy) {
x = xx;
y = yy;
}
};
int Next[4][2] = {0,1,1,0,0,-1,-1,0};
void bfs(int x,int y,int color)
{
queue< Node> q;
mpp[x][y] = color;
q.push(Node(x,y));
int tx,ty;
while(!q.empty()) {
Node s = q.front();
for(int i=0;i<4;i++) {
tx = s.x+Next[i][0];
ty = s.y+Next[i][1];
if(tx < 1 || tx > n || ty < 1 || ty > n)
continue;
if(mp[tx][ty] == '#' && mpp[tx][ty] == 0) {
mpp[tx][ty] = color;
q.push(Node(tx,ty));
}
}
q.pop();
}
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%s",mp[i]+1);
int color = 1;
for(int i=2;i<n;i++) {
for(int j=2;j<n;j++) {
if(mp[i][j] == '#' && mpp[i][j] == 0) {
bfs(i,j,color);
color++;
}
}
}
for(int i=2;i<n;i++) {
for(int j=2;j<n;j++) {
if(mp[i][j] == '#' && (mp[i][j-1] == '.' || mp[i][j+1] == '.' || mp[i+1][j] == '.' || mp[i-1][j] == '.'))
mpp[i][j] = 0;
}
}
int tot;
for(int i=2;i<n;i++) {
for(int j=2;j<n;j++) {
if(mpp[i][j] != 0)
book[mpp[i][j]]= true;
}
}
for(int i=1;i<color;i++)
if(!book[i])
tot++;
cout << tot << endl;
}