BFS模拟跑一遍就行
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <cstring>
#include <vector>
#include <set>
using namespace std;
#define ll long long
#define maxn 100005
struct Node
{
int x, y, cnt;
Node()
{
x = 0; y = 0; cnt = 0;
}
Node(int x, int y, int cnt)
{
this->x = x; this->y = y;
this->cnt = cnt;
}
};
const int dx[4] = { 0, 0, 1, -1 };
const int dy[4] = { 1, -1, 0, 0 };
char grid[505][505];
int cnt[505][505];
int R, C;
inline bool legal(int x, int y)
{
if (x >= 0 && x < R&&y >= 0 && y < C)
return true;
else
return false;
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int T;
scanf("%d", &T);
while (T--)
{
memset(grid, 0, sizeof(char) * 505 * 505);
memset(cnt, 0, sizeof(int) * 505 * 505);
scanf("%d%d", &R, &C);
for (int i = 0; i < R; ++i)
{
scanf("%s", grid[i]);
}
queue<Node> Q;
for (int i = 0; i < R; ++i)
{
for (int j = 0; j < C; ++j)
{
if (grid[i][j] >= 'a'&&grid[i][j] <= 'z')
{
Q.push(Node(i, j, 0));
//printf("node %d %d\n", i, j);
}
}
}
Node t;
int x1, y1;
while (!Q.empty())
{
t = Q.front();
Q.pop();
if (grid[t.x][t.y] == '*')
continue;
for (int i = 0; i < 4; ++i)
{
x1 = t.x + dx[i];
y1 = t.y + dy[i];
if (legal(x1, y1))
{
//printf("x1 %d y1 %d\n", x1, y1);
if (grid[x1][y1] == '.')
{
//printf("in x1 %d y1 %d\n", x1, y1);
grid[x1][y1] = grid[t.x][t.y];
Q.push(Node(x1, y1, t.cnt + 1));
cnt[x1][y1] = t.cnt + 1;
}
else if (grid[x1][y1] >= 'a'&&grid[x1][y1] <= 'z'&&grid[t.x][t.y]!=grid[x1][y1])
{
if (t.cnt + 1 == cnt[x1][y1])
grid[x1][y1] = '*';
}
}
}
}
for (int i = 0; i < R; ++i)
{
printf("%s\n", grid[i]);
}
printf("\n");
}
//printf("\n");
//system("pause");
//while (1);
return 0;
}