问题描述
小明有一块空地,他将这块空地划分为 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