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;
}

最后提交:

相关推荐
花火|29 分钟前
算法训练营day55 图论⑤ 并查集理论基础、107. 寻找存在的路径
算法·图论
花火|31 分钟前
算法训练营day56 图论⑥ 108. 109.冗余连接系列
算法·图论
上海迪士尼3531 分钟前
力扣子集问题C++代码
c++·算法·leetcode
花开富贵ii32 分钟前
代码随想录算法训练营四十六天|图论part04
java·数据结构·算法·图论
SunnyKriSmile34 分钟前
【冒泡排序】
c语言·算法·排序算法
熬了夜的程序员34 分钟前
【LeetCode】16. 最接近的三数之和
数据结构·算法·leetcode·职场和发展·深度优先
小亮✿35 分钟前
算法——快速幂
算法
Miraitowa_cheems36 分钟前
LeetCode算法日记 - Day 15: 和为 K 的子数组、和可被 K 整除的子数组
java·数据结构·算法·leetcode·职场和发展·哈希算法
金融小师妹1 小时前
AI多因子模型解析:黄金涨势受阻与美联储9月降息政策预期重构
大数据·人工智能·算法