这道题是一个联通块的问题,可以用深搜,广搜,并查集做,这里我用的是广搜。
但是裸BFS会T三个点,因为数据太大了。这时我们可以想一下联通块,只要某一些点在同一个联通块里面,那么他们的答案肯定是相同的,所以我们可以用一个数组把这些点都标成同一个答案,这样就不用每一次都重置VIS数组
上代码:
#include <bits/stdc++.h>
#include <queue>
#define LL long long
#define x first
#define y second
#define PII pair<int, int>
using namespace std;
const int N = 1e3 + 10;
const int M = 1e5 + 10;
//typedef long long LL;
int n, m, sum, sx, sy;
int idx = 0;
char Map[N][N];//存点
bool vis[N][N];//判断这个点是否被搜索过
int book[N][N];//储存每一个点的答案
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
inline int read()
{
int sum = 0;
char ch = getchar();
while (ch < '0' || ch >'9')
ch = getchar();
while (ch <= '9' && ch >= '0')
sum = sum * 10 + ch - 48, ch = getchar();
return sum;
}
void bfs(int ax, int ay)//经典BFS
{
queue <PII> q;
queue <PII> pos;//用来存我们每一次搜索过的点,在这个队列里的点都属于同一个联通块,答案相同
q.push({ ax,ay });
pos.push({ ax, ay });
vis[ax][ay] = 1;
while (q.size())
{
PII t = q.front();
q.pop();
for (int i = 0; i < 4; ++i)
{
int xx = t.x + dx[i], yy = t.y + dy[i];
if (xx<1 || xx>n || yy<1 || yy>n)
continue;
if (vis[xx][yy])
continue;
if (Map[t.x][t.y] == '0')
if (Map[xx][yy] == '0')
continue;
if (Map[t.x][t.y] == '1')
if (Map[xx][yy] == '1')
continue;
vis[xx][yy] = 1;
q.push({ xx,yy });
pos.push({ xx,yy });
sum++;
}
}
while (!pos.empty())//在把这些队列里的点全部标成相同的
{
PII t = pos.front();
pos.pop();
int xx = t.x, yy = t.y;
book[xx][yy] = sum;
}
}
int main()
{
memset(book, 0, sizeof book);
n = read(), m = read();
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
cin >> Map[i][j];
for (int i = 1; i <= m; ++i)
{
sum = 1;
sx = read(), sy = read();
if (vis[sx][sy] != 0)//不用重置了,看看这个点搜索过没有,搜过的话直接输出
{
cout << book[sx][sy] << endl;
}
else//没有搜索的话就搜索一次
{
bfs(sx, sy);
book[sx][sy] = sum;
cout << sum << endl;
}
}
return 0;
}