P1506 拯救oibh总部(BFS洪水灌溉)

题目:

样例1:

|-----------------------------|
| 4 5 00000 0000 000 0000 |
[输入]

|---|
| 1 |
[输出]

样例2:

|-----------------------------------|
| 5 5 ***** 00* 0 00* ***** |
[输入]

|---|
| 5 |
[输出]

思路:

洪水灌溉,思路:给该图外面包围一圈可遍历的的点,作为引流灌溉。

BFS外围一点,即可顺流而下的灌溉下去。

代码详解如下:

cpp 复制代码
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#define endl '\n'
#define YES puts("YES")
#define NO puts("NO")
#define mk make_pair
#define x first
#define y second
#define umap unordered_map
#define All(x) x.begin(),x.end()
#pragma GCC optimize(3,"Ofast","inline")
#define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;
const int N = 2e6 + 10;
using PII = pair<int,int>;
int n,m;
umap<int,string>g;// 地图

int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};

inline bool isRun(int x,int y)
{
	return (x >= 0 && x < n && y >= 0 &&y < m && g[x][y] == '0');
}

inline void BFS(int tx,int ty)
{
	queue<PII>q;
	
	q.emplace(mk(tx,ty));
	
	while(q.size())
	{
		PII now = q.front();
		q.pop();
		
		g[now.x][now.y] = '1';	// 标记被灌溉的点
		
		for(int i = 0;i < 4;++i)
		{
			int bx = now.x + dx[i];
			int by = now.y + dy[i];
			if(isRun(bx,by))
			{
				g[bx][by] = '1';	// 标记被灌溉的点
				q.emplace(mk(bx,by));
			}
		}
	}
}


inline void solve()
{
	cin >> n >> m;
	m += 2;	// 由于建了外圈,所以宽度 +2
	
	// 建立上下外圈
	for(int i = 0;i < m;++i)
	{
		g[0] += "0";
		g[n + 1] += "0";
	} 
	
	for(int i = 1;i <= n;++i)
	{
		// 这里是输入地图后,建立两边的外圈
		string s;
		cin >> s;
		g[i] = "0" + s + "0";
	}	
	
	n += 2;	// 由于建立了上下外圈,所以高 + 2
	
	BFS(0,0);	// 引流灌溉
	
	// 获取未被洪水淹没的重要区域
	int ans = 0;
	for(int i = 0;i < n;++i)
	{
		for(int j = 0;j < m;++j)
		{
			if(g[i][j] == '0') ++ans;
		}
	}
	
	cout << ans << endl;
}

int main()
{
//	freopen("a.txt", "r", stdin);
	IOS;
	int _t = 1;
//	cin >> _t;
	while (_t--)
	{
		solve();
	}

	return 0;
}

最后提交:

相关推荐
不正经学生1 小时前
C语言预处理详解:编译器真正动手之前的那些事
c语言·开发语言·算法·面试·bug
毕竟是shy哥4 小时前
计算YOLO数据集中每个类的目标数
算法·yolo·机器学习
M78佐菲4 小时前
Linux学习笔记:TCP协议
linux·笔记·学习·tcp/ip·算法
晊晌_h5 小时前
嵌入式从0到精通——数据结构总结[特殊字符]
数据结构·算法·排序算法
我找到地球的支点啦6 小时前
Matlab系列(009) 一CRC循环冗余校验详解
开发语言·数据结构·算法·matlab·信息与通信
罗西的思考6 小时前
【OpenClaw具身硬件】ZeroClaw 源码阅读笔记(3)--- RAG
人工智能·算法·机器学习
浪里镖客7 小时前
位姿转换矩阵写法-个人习惯(计算机理解其实是相反的)
线性代数·算法·矩阵
小白羊丨10 小时前
如何诊断 Prompt 模板导致的效果下降?
人工智能·算法·prompt
OPEN-F11 小时前
C++11/14新特性精讲:移动语义与智能指针实战
开发语言·c++·算法
lisin-lee-cooper11 小时前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法