全球变暖

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

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

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

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

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

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

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

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

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

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

【输入样例】
7

.##…
.##…
…##.
…####.
…###.

【输出样例】
1

参考代码:

#include<bits/stdc++.h> 
using namespace std;
const int maxn = 1001;
char a[maxn][maxn];
const int f[4] = {1,0,0,-1};
const int g[4] = {0,-1,1,0};
typedef pair<int,int>p;
void bfs(int x,int y)
{
	queue<p>que;
	que.push(p(x,y));
	a[x][y] = '1';
	while(!que.empty())
	{
		int m = que.front().first;
		int n = que.front().second;
		que.pop();
		for(int i = 0; i < 4; i++)
		{
			int nx = m+f[i];
			int ny = n+g[i];
			if(a[nx][ny] == '#')
			{
				a[nx][ny] = '1';	//遍历过记为1 
				que.push(p(nx,ny));
			}				
		}		
	}
}
void destory(int x,int y)
{
	if(a[x-1][y] == '.' || a[x+1][y] == '.' || a[x][y+1] == '.' ||a[x][y-1] == '.')
	{
		a[x][y] = '0';	//被销毁记为0 
	}
} 
int main()
{
	int n;
	cin>>n;
	int cnt = 0,end = 0,result;
	for(int i = 0; i < n; i++)
		scanf("%s",a+i);	
	for(int i = 0; i < n; i++)	
	{
		for(int j = 0; j < n; j++)
		{
			if(a[i][j] == '#')
			{
				bfs(i,j);
				cnt++;	//找出原来岛的数量 
			}	
		}
	}
	for(int i = 0; i < n; i++)	
	{
		for(int j = 0; j < n; j++)
		{
			if(a[i][j] == '1')
			{
				destory(i,j);//毁灭岛 
			}	
		}
	}
	for(int i = 0; i < n; i++)	
	{
		for(int j = 0; j < n; j++)
		{
			if(a[i][j] == '1')
			{
				bfs(i,j);
				end++;	//找出剩下岛的数量 
			}	
		}
	}	
	result = cnt-end;	//原来岛的数量-剩下的 = 被销毁的 
	if(result > 0)	
		cout<<result<<endl;
	else
		cout<<"0"<<endl;	//剩下的可能比原来多
	return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值