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

最后提交:

相关推荐
rannn_1114 小时前
【力扣hot100】链表专题|160、206、234、141、142
java·算法·leetcode·链表·面试·开发
数模竞赛Paid answer4 小时前
2026年华东杯数学建模B题医药物流安排问题解题全过程文档及程序
算法·数学建模·数据分析·华东杯
不会代码的小猴4 小时前
21. 泛型编程上
开发语言·c++·笔记·算法
AI备案指南-满满5 小时前
大模型与算法备案全流程详解:从零到通过的完整指南
人工智能·算法·备案·大模型备案·算法备案
江畔柳前堤5 小时前
LLM 训练核心机制深度解析:Warmup、Cosine Decay 与 Perplexity 的完整知识体系
网络·人工智能·深度学习·算法·机器学习·语音识别
一只旭宝5 小时前
细讲C加加【9】C++ std::function与std::bind详解|仿函数、绑定器、类成员绑定、占位符、成员偏移指针
开发语言·c++·算法
良木林6 小时前
子串 - LeetCode hot 100
算法·leetcode·职场和发展
陌诺曦.6 小时前
Python扩展小练习
算法
coder!mq7 小时前
说几个常见的语法糖?
java·开发语言·算法