花园灌溉问题
#include <bits/stdc++.h>
using namespace std;// 设置最大行列数(题目限制 n, m ≤ 100)
const int N = 104;// 标记某个格子是否已经被水浇灌
bool used[N][N];// 队列,用于 BFS,存储当前水源的位置
queue<pair<int,int>> q;int main()
{// 加速输入输出ios::sync_with_stdio(false);cin.tie(nullptr);// 定义四个方向:下、右、上、左(顺时针)int dx[4] = {1,0,-1,0};int dy[4] = {0,1,0,-1};int cnt = 0; // 被浇灌的格子数量int n, m;cin >> n >> m; // 输入行数n、列数mint t;cin >> t; // 初始出水管的数量int r, c;for(int i = 1; i <= t; i++){cin >> r >> c; // 出水管的位置(行r,列c)used[r][c] = true; // 标记该格子已被浇灌q.push({r, c}); // 加入队列作为初始水源cnt++; // 计入被浇灌的格子}int k;cin >> k; // 经过的分钟数,每分钟水扩展一轮// 开始 BFS,每分钟扩展一轮while(k--){int sz = q.size(); // 当前层级(水源)数量while(sz--){auto [x, y] = q.front(); // 当前水源位置q.pop();// 尝试向四个方向扩展for(int j = 0; j < 4; j++){int nextx = x + dx[j];int nexty = y + dy[j];// 判断是否在范围内,且尚未被浇灌if(nextx >= 1 && nextx <= n && nexty >= 1 && nexty <= m && !used[nextx][nexty]){used[nextx][nexty] = true; // 标记为已浇灌q.push({nextx, nexty}); // 新位置加入队列,下一轮会扩展cnt++; // 增加总浇灌格子数量}} }}// 输出最终被浇灌的格子数量cout << cnt << endl;return 0;
}
#include <bits/stdc++.h>
using namespace std;
const int N = 104;bool used[N][N];
queue<pair<int,int>> q;int main()
{ios::sync_with_stdio(false);cin.tie(nullptr);int dx[4] = {1,0,-1,0};int dy[4] = {0,1,0,-1};int cnt =0;int n,m;cin >> n >> m;int t;cin >> t;int r ,c;for(int i=1;i<=t;i++){cin >> r >> c;used[r][c]=true;q.push({r,c});cnt ++;}int k;cin >> k;while(k--){int sz=q.size();while(sz--){auto [x,y] = q.front();q.pop();for(int j=0;j<4;j++){int nextx= x + dx[j];int nexty = y + dy[j];if(nextx>=1 && nextx <=n && nexty >=1 && nexty <=m && !used[nextx][nexty]){cnt++;used[nextx][nexty] =true;q.push({nextx,nexty});}} }}cout << cnt << endl;return 0;}
#include <bits/stdc++.h>
using namespace std;const int N = 105;
bool used[N][N];int main()
{ios::sync_with_stdio(false);cin.tie(nullptr);int n, m;cin >> n >> m;int t;cin >> t;queue<pair<int, int>> q;for (int i = 0; i < t; i++) {int r, c;cin >> r >> c;used[r][c] = true;q.push({r, c});}int k;cin >> k;int dx[4] = {1, 0, -1, 0};int dy[4] = {0, 1, 0, -1};while (k--) {int sz = q.size();while (sz--) {auto [x, y] = q.front(); q.pop();for (int d = 0; d < 4; d++) {int nx = x + dx[d];int ny = y + dy[d];if (nx >= 1 && nx <= n && ny >= 1 && ny <= m && !used[nx][ny]) {used[nx][ny] = true;q.push({nx, ny});}}}}int cnt = 0;for (int i = 1; i <= n; i++)for (int j = 1; j <= m; j++)if (used[i][j]) cnt++;cout << cnt << endl;return 0;
}
551