全球变暖(蓝桥杯 2018 年第九届省赛)

题目描述

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

复制代码
.......
.##....
.##....
....##.
..####.
...###.
.......

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

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

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

复制代码
.......
.......
.......
.......
....#..
.......
.......

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

输入格式

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

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

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

输出格式

一个整数表示答案。

输入输出样例

输入

复制代码
7 
.......
.##....
.##....
....##.
..####.
...###.
.......  

输出

复制代码
1

说明/提示

时限 1 秒, 256M。

//代码如下:

复制代码
//全球变暖问题的本质是:
//寻找连通块 遍历连通块 在连通块的范围内寻找一块陆地(就够了,足以证明整个连通块不会被淹没) 
//记得将整个连通块寻找完全 建议使用dfs搜索
 
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>

using namespace std;
//存储图
vector<string> picture;
//访问数组
vector<vector<bool>>  visited;
//方位数组
int indexx[]={0,0,-1,1};
int indeyy[]={-1,1,0,0};
//图的边长
int N; 
//标志整个连通块是不是被淹没
bool flag; 
//存储坐标
typedef struct Node{
	int x;
	int y;
	Node(int x,int y):x(x),y(y){}
}Node; 
//存储没有被淹没的连通块
int ans=0; 

void dfs(int x,int y){
	//剪枝操作
	if(x<0||x>N||y<0||y>N||visited[x][y]||picture[x][y]!='#') return;
	 //每次只处理一个陆地 
	if(!flag){
		int cnt=0;
		
	for(int i=0;i<4;i++){
		int newx=x+indexx[i];
		int newy=y+indeyy[i];
		if(0<=newx&&newx<N&&0<=newy&&newy<N&&picture[newx][newy]=='#') {
			cnt++;}
	}
	
		if(cnt==4){
			//整个连通块不可能被淹没 
			flag=true;
			ans++;
			}	
			//将处理过的连通块中的一部分陆地标记 
	}

	//继续处理连通块知道整个连通块都被搜索出来 
	visited[x][y]=true;
	for(int i=0;i<4;i++){
		int newx=x+indexx[i];
		int newy=y+indeyy[i];
		
		if(newy<0||newy>N||newy<0||newy>N||visited[newx][newy]||picture[newx][newy]!='#')continue;
		dfs(newx,newy);}
		//直到整个连通块都被处理掉 
		return ;
}
int main(){
	//图的边长 
	cin>>N;
	//存储图 
	for(int i=0;i<N;i++) {
		string ss;
		cin>>ss;
		picture.push_back(ss);}
	//存储被访问数组 
	for(int i=0;i<N;i++){
		vector<bool> ss(N,false);
		visited.push_back(ss);}
	//遍历整张图 
	//记录开始岛屿数量
	int rans=0;
	for(int row=0;row<N;row++){
		
		for(int col=0;col<N;col++){
				//记录这个位置 
				//继续寻找下一个连通块 
			if(picture[row][col]=='#'&&!visited[row][col]){
				rans++;
				flag=false;
				dfs(row,col);
			}
		}
	}
	//输出答案 
	cout<<rans-ans<<endl;
	return 0;
}
/*
5
.....
.###.
.###.
.###.
.....

9
.........
.#######.
.#######.
.#######.
..#.#....
.#######.
.#######.
.#######.
.........
*/
相关推荐
聚客AI2 小时前
🙋‍♀️Transformer训练与推理全流程:从输入处理到输出生成
人工智能·算法·llm
大怪v4 小时前
前端:人工智能?我也会啊!来个花活,😎😎😎“自动驾驶”整起!
前端·javascript·算法
惯导马工6 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法
骑自行车的码农8 小时前
【React用到的一些算法】游标和栈
算法·react.js
博笙困了8 小时前
AcWing学习——双指针算法
c++·算法
moonlifesudo8 小时前
322:零钱兑换(三种方法)
算法
NAGNIP1 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法