模拟长草(bfs)

问题描述
小明有一块空地,他将这块空地划分为 n 行 m 列的小块,每行和每列的长度都为 1。
小明选了其中的一些小块空地,种上了草,其他小块仍然保持是空地。
这些草长得很快,每个月,草都会向外长出一些,如果一个小块种了草,则它将向自己的上、下、左、右四小块空地扩展,这四小块空地都将变为有草的小块。
请告诉小明,k 个月后空地上哪些地方有草。
输入格式
输入的第一行包含两个整数 n, m。
接下来 n 行,每行包含 m 个字母,表示初始的空地状态,字母之间没有空格。如果为小数点,表示为空地,如果字母为 g,表示种了草。
接下来包含一个整数 k。
输出格式
输出 n 行,每行包含 m 个字母,表示 k 个月后空地的状态。如果为小数点,表示为空地,如果字母为 g,表示长了草。
样例输入
4 5
.g…
.….
…g…
.….
2
样例输出
gggg.
gggg.
ggggg
.ggg.

#include <iostream>
#include <bitset>
#include <algorithm>
#include <cmath>
#include <ctype.h>
#include <string>
#include <cstdio>
#include <set>
#include <cstdio>
#include <fstream>
#include <deque>
#include <vector>
#include <queue>
#include <map>
#include <stack>
#include <iomanip>
#define SIS std::ios::sync_with_stdio(false)
#define ll long long
#define INF 0x3f3f3f3f
const int mod = 1e9 + 7;
const double esp = 1e-5;
const double PI = 3.141592653589793238462643383279;
using namespace std;
const int N = 1e7 + 5;
const int maxn = 1 << 20;
ll powmod(ll a, ll b) { ll res = 1; a %= mod; while (b >= 0); for (; b; b >>= 1) { if (b & 1)res = res * a % mod; a = a * a % mod; }return res; }
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
/*void chafen(int l, int r, int k) {//差分函数
	p[l] += k;
	p[r + 1] -= k;
}*/
/*************************************************************/	
char s[1005][1005];
typedef struct  {
	int x, y;
	int cnt;
}P;
int main() {
	int n, m;
	int k;
	cin >> n >> m;
	for (int i = 0; i < n; i++)
		cin >> s[i];
	cin >> k;
	P temp;
	queue<P> q;
	for(int i=0;i<n;i++)
		for (int j = 0; j < m; j++) {
			if (s[i][j] == 'g') {//看成多起点
				temp.x = i;
				temp.y = j;
				temp.cnt = 0;
				q.push(temp);
			}
		}
	while (!q.empty()) {
		P mod = q.front();
		s[mod.x][mod.y] = 'g';
		q.pop();
		if (mod.cnt != k) {
		    for(int i=-1;i<=1;i++)
			    for (int j = -1; j <= 1; j++) 
					if (!i || !j) {
						temp.x = mod.x+i;
						temp.y = mod.y+j;
						temp.cnt = mod.cnt + 1;
						if (temp.x<0 || temp.x>=n || temp.y<0 || temp.y>=m)
							continue;
						q.push(temp);
					}
			    
		}
	}
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++)
			cout << s[i][j];
		cout << endl;
	}
	cout << endl;
	return 0;
}
/*
4 5
.g...
.....
..g..
.....
2
*/

普通bfs

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

deebcjrb

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值