题目:给定一个n*m的地图,有k次查询。每次查询,询问位置(x,y)的点连通块周围有多少个*
思路:k的范围有点大,如果对每一次查询都DFS一次的话肯定超时,所以输入地图后直接暴力先DFS每一个点连通块周围的*的数量记录下来,对每次询问直接输出即可
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 1001
#define LL long long
int cas=1,T;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
char mapp[maxn][maxn];
int vis[maxn][maxn];
int num[maxn*maxn];
int ans,id=0,m,n;
void dfs(int x,int y)
{
int nx,ny;
vis[x][y]=id;
for (int i = 0;i<4;i++)
{
nx = x+dir[i][0];
ny = y+dir[i][1];
if (nx>0 && nx<=n && ny>0 && ny<=m && !vis[nx][ny])
{
if (mapp[nx][ny] == '*')
ans++;
else
dfs(nx,ny);
}
}
}
int main()
{
int k;
scanf("%d%d%d",&n,&m,&k);
for (int i = 1;i<=n;i++)
scanf("%s",mapp[i]+1);
memset(vis,0,sizeof(vis));
for (int i = 1;i<=n;i++)
for (int j = 1;j<=m;j++)
if (mapp[i][j] == '.' && !vis[i][j])
{
ans = 0;
id++;
dfs(i,j);
num[id]=ans;
}
while (k--)
{
int x,y;
scanf("%d%d",&x,&y);
printf("%d\n",num[vis[x][y]]);
}
//freopen("in","r",stdin);
//scanf("%d",&T);
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return 0;
}