第 1 题:长草
#include <bits/stdc++.h>
using namespace std;
queue<pair<int, int> > grass;
int n, m, k;
char Map[1001][1001];
int dire[][2] = { {1,0},{-1,0},{0,1},{0,-1} };
void grow(int x, int y)
{
for (int i = 0; i < 4; i++)
{
int newx = x + dire[i][0];
int newy = y + dire[i][1];
if (newx < 1 || newy < 1 || newx > n || newy > m)continue;
if (Map[newx][newy] != 'g')
{
Map[newx][newy] = 'g';
grass.push(pair<int, int>(newx, newy));
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cin >> Map[i][j];
if (Map[i][j] == 'g')
{
grass.push(pair<int, int>(i, j));
}
}
}
cin >> k;
int t = grass.size();
while (!grass.empty() && k > 0)
{
int x = grass.front().first;
int y = grass.front().second;
grass.pop();
grow(x, y);
t--;
if (t == 0)
{
k--;
t = grass.size();
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
cout << Map[i][j];
}
cout << endl;
}
}
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3+10;
int nex[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
int n,k;
int a[N][N],s[N][N];
bool vis[N][N];
struct node {
int x,y;
int ret;
int status;
};
bool check(int x, int y, int status) {
if (x < 1 || x > n || y < 1 || y > n || a[x][y] == 3) return false;
if (a[x][y] == 2 && !status) return false;
return true;
}
int bfs(int x, int y) {
queue<node> que;
que.push({x,y,0,0});
vis[x][y] = true;
while (que.size()) {
auto t = que.front();
que.pop();
int u = t.x, v = t.y;
if (u == n && v == n) return t.ret;
for (int i = 0; i < 4; i++) {
int tx = u + nex[i][0];
int ty = v + nex[i][1];
if (!check(tx,ty,t.status)) continue;
int status = max(t.status-1,0);
if (a[tx][ty] == 1) {
a[tx][ty] = 0;
vis[tx][ty] = true;
que.push({tx,ty,t.ret+1,k});
}
else {
if (!vis[tx][ty]) {
vis[tx][ty] = true;
que.push({tx,ty,t.ret+1,status});
continue;
}
if (status <= s[tx][ty]) continue;
s[tx][ty] = status;
que.push({tx,ty,t.ret+1,max(0,status)});
}
}
}
return -1;
}
int main() {
cin >> n >> k;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
char x;
cin >> x;
if (x == '%') a[i][j] = 1;
else if (x == 'X') a[i][j] = 2;
else if (x == '#') a[i][j] = 3;
}
}
cout << bfs(1,1) << endl;
}