题意:给你一个图, 在每一个'.'和'*'之间放了一副画,给你一个点求那个地方(只要'.'相连的区域)的画的数目。
直接模拟肯定会超时,所以我们要先如预处理。
我用dfs求每一个地区画的数目,然后用在对每一个点都赋这个值。
#include
#include
#include
#include
using namespace std;
const int N = 1001;
char str[N][N];
int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
int n, m ,k;
int vis[N][N];
int ans[N][N];
int dfs(int x, int y)
{
int ans = 0;
int i;
for(i = 0; i < 4; i++)
{
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if(0 <= xx && xx < n && 0 <= yy && yy < m )
{
if(str[xx][yy] == '.')
{
if(!vis[xx][yy])
{
vis[xx][yy] = 1;
ans += dfs(xx, yy);
}
}
else ans++;
}
}
return ans;
}
int dfs1(int x, int y, int val)
{
int i;
for(i = 0; i < 4; i++)
{
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if(0 <= xx && xx < n && 0 <= yy && yy < m )
{
if(vis[xx][yy] && !ans[xx][yy])
{
ans[xx][yy] = val;
dfs1(xx, yy, val);
}
}
}
return 0;
}
int main(void)
{
int i, j;
scanf("%d%d%d", &n, &m, &k);
for(i = 0; i < n; i++)
{
scanf("%s", str[i]);
}
memset(vis, 0, sizeof(vis));
for(i = 0; i < n; i++)
{
for(j = 0; j < m; j++)
{
if(str[i][j] == '.' && !vis[i][j])
{
vis[i][j] = 1;
ans[i][j] = dfs(i, j);
dfs1(i, j, ans[i][j]);
}
}
}
while(k--)
{
int x, y;
scanf("%d%d", &x, &y);
printf("%d\n", ans[x-1][y-1]);
}
return 0;
}