模擬長草(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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章