01迷宫
2025年2月26日小于 1 分钟
#include <bits/stdc++.h>
using namespace std;
char g[1003][1003];
int vis[1003][1003];
int dx[] = {0, 1, 0, -1}, dy[] = {-1, 0, 1, 0}, nx, ny, n, m;
int now, ans[1003][1003];
//“可变长数组”
//ax.clear();
//ax.size();
//ax.push_back(x);
//ax[i]
vector<int> ax, ay; //记录dfs走过的点
void dfs(int x, int y, int flag)
{
vis[x][y] = flag; //标记当前位置走过了
now++; //当前能走到的点多一个
ax.push_back(x); //储存dfs走过的路
ay.push_back(y);
for (int i = 0; i < 4; i++)
{
nx = x + dx[i];
ny = y + dy[i];
if (g[x][y] == g[nx][ny])
continue;
if (nx && ny && nx <= n && ny <= n)
if (vis[nx][ny] != flag)
dfs(nx, ny, flag);
}
}
int main()
{
//输入
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
cin >> g[i][j];
//处理每个询问
memset(vis, 0, sizeof(vis));
memset(ans, -1, sizeof(ans));
for (int i = 1; i <= m; i++)
{
int x, y;
cin >> x >> y;
if (ans[x][y] == -1)
{
now = 0;
dfs(x, y, i);
//dfs路径上所有点可以走到的点的数量设置为now
for (int i = 0; i < ax.size(); i++)
ans[ax[i]][ay[i]] = now;
ax.clear();
ay.clear();
}
cout << ans[x][y] << endl;
}
}