标题:全球变暖
你有一张某海域NxN像素的照片,"."表示海洋、"#"表示陆地,如下所示:
.......
.##....
.##....
....##.
..####.
...###.
.......
其中"上下左右"四个方向上连在一起的一片陆地组成一座岛屿。例如上图就有2座岛屿。
由于全球变暖导致了海面上升,科学家预测未来几十年,岛屿边缘一个像素的范围会被海水淹没。具体来说如果一块陆地像素与海洋相邻(上下左右四个相邻像素中有海洋),它就会被淹没。
例如上图中的海域未来会变成如下样子:
.......
.......
.......
.......
....#..
.......
.......
请你计算:依照科学家的预测,照片中有多少岛屿会被完全淹没。
【输入格式】
第一行包含一个整数N。 (1 <= N <= 1000)
以下N行N列代表一张海域照片。
照片保证第1行、第1列、第N行、第N列的像素都是海洋。
【输出格式】
一个整数表示答案。
【输入样例】
7
.......
.##....
.##....
....##.
..####.
...###.
.......
【输出样例】
1
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms
思路:深搜岛屿然后处理淹没范围最后判断,有一点值得注意的是有可能海水侵蚀完后可能岛屿更多了,就是类似于这样的样例容易出错.
我是记录原岛屿由哪些点组成,侵蚀后看看这些点还有没有存活的.
代码:
#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
const double esp = 1e-7;
const int ff = 0x3f3f3f3f;
map<int,int>::iterator it;
struct node
{
int x,y;
node(int x = 0,int y = 0):x(x),y(y){}
};
int n;
int cnt;
char mp[1005][1005];
int vis[1005][1005];
vector<node> d[maxn];
int ne[4][2] = {1,0,-1,0,0,1,0,-1};
void find(int x,int y)//寻找相连点
{
d[cnt].push_back(node(x,y));
vis[x][y] = 1;
for(int i = 0;i< 4;i++)
{
int tx = x+ne[i][0];
int ty = y+ne[i][1];
if(tx< 0||tx>= n||ty< 0||ty>= n||vis[tx][ty]||mp[tx][ty] == '.')
continue;
find(tx,ty);
}
return ;
}
void Preprocess()//预处理岛屿
{
for(int i = 0;i< n;i++)
for(int j = 0;j< n;j++)
if(mp[i][j] == '#'&&!vis[i][j])
{
cnt++;
find(i,j);
}
return ;
}
void dfs(int x,int y)//侵蚀
{
vis[x][y] = 1;
for(int i = 0;i< 4;i++)
{
int tx = x+ne[i][0];
int ty = y+ne[i][1];
if(tx< 0||tx>= n||ty< 0||ty>= n||vis[tx][ty])
continue;
if(mp[tx][ty] == '#')
vis[tx][ty] = 1;
else
dfs(tx,ty);
}
return ;
}
void solve()//开始侵蚀
{
mem(vis,0);
for(int i = 0;i< n;i++)
for(int j = 0;j< n;j++)
if(mp[i][j] == '.'&&!vis[i][j])
dfs(i,j);
return ;
}
int main()
{
cin>>n;
for(int i = 0;i< n;i++)
scanf(" %s",mp[i]);
Preprocess();
solve();
int ans = 0;
for(int i = 1;i<= cnt;i++)//判断组成岛屿的点还在不在
{
int j,k = d[i].size();
for(j = 0;j< k;j++)
if(vis[d[i][j].x][d[i][j].y] == 0)
break;
if(j == k)
ans++;
}
cout<<ans<<endl;
return 0;
}