编辑代码

#include <bits/stdc++.h>
using namespace std;

struct Node { 
    int x, y, k; 
};

int main() {
    ios::sync_with_stdio(0); 
    cin.tie(0);
    
    int n, m, k;
    cin >> n >> m;
    
    vector<vector<int>> ans(n+2, vector<int>(m+2, 0));
    vector<vector<bool>> visit(n+2, vector<bool>(m+2, false));
    
    int dx[] = {0, 0, -1, 1};
    int dy[] = {1, -1, 0, 0};
    
    // 输入网格
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            char in;
            cin >> in;
            ans[i][j] = (in == 'g') ? 1 : 0;
        }
    }
    
    cin >> k;
    queue<Node> q;
    
    // 初始草位置入队并标记
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (ans[i][j] == 1) {
                q.push({i, j, k});
                visit[i][j] = true;
            }
        }
    }
    
    // BFS扩散
    while (!q.empty()) {
        Node current = q.front();
        q.pop();
        
        if (current.k == 0) continue;
        
        for (int i = 0; i < 4; i++) {
            int nx = current.x + dx[i];
            int ny = current.y + dy[i];
            
            if (nx >= 1 && nx <= n && ny >= 1 && ny <= m) {
                if (!visit[nx][ny]) {
                    ans[nx][ny] = 1;
                    visit[nx][ny] = true;
                    q.push({nx, ny, current.k-1});
                }
            }
        }
    }
    
    // 输出结果
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            cout << (ans[i][j] ? 'g' : '.');
        }
        cout << "\n";
    }
    
    return 0;
}