トピックの説明
Xiao Ming には空きスペースがあり、空きスペースを nn 行 mm 列の小さなブロックに分割し、各行と列の長さは 1 です。
Xiao Ming は、いくつかの小さなオープン スペースを選び、草を植えましたが、他の小さなエリアはオープンのままでした。
草は非常に速く成長し、毎月、草は外側に成長します. 小さな区画に草を植えると、上、下、左、右の4つの小さな空き地に広がります.
4つのオープンスペースのそれぞれが芝生になります。kkヶ月後にオープンスペースのどこに草があるかシャオミンに教えてください.
問題解決のアイデア
BFS アルゴリズムの概要 (迷路歩行問題) を参照してください。
コード
#include <bits/stdc++.h>
using namespace std;
char a[10000][10000];
struct node {
int x;
int y;
};
queue<node> q;
int dx[] = {0, 1, 0, -1}; //左右上下
int dy[] = {1, 0, -1, 0}; //左右上下
int main() {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> a[i][j];
if (a[i][j] == 'g') {
node newNode;
newNode.x = i;
newNode.y = j;
q.push(newNode);
}
}
}
int k;
cin >> k;
while (k--) {
int len = q.size();
while (len--) {
int x = q.front().x;
int y = q.front().y;
for (int i = 0; i < 4; i++) {
int tx = x + dx[i]; //周边节点的X轴
int ty = y + dy[i]; //周边节点的y轴
if (a[tx][ty] == '.') {
a[tx][ty] = 'g';
node newNode;
newNode.x = tx;
newNode.y = ty;
q.push(newNode);
}
}
q.pop();
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cout << a[i][j];
cout << endl;
return 0;
}