E - Igor In the Museum (dfs)
CCPC-Wannafly Summer Camp 2019 Day1 原题连接
题目大意
给你一个n*m的方格图表示一个博物馆的分布图.
每个方格上用'*'表示墙,用'.'表示空位.
每一个空格和相邻的墙之间都有一幅画.
(相邻指的是上下左右相邻).
你可以从一个空格的位置走到相邻的空格位置.
现在你给你若干个(xi,yi)形式的询问,
表示你现在在(xi,yi)这个位置(保证为空位)出发,
问你从这个点出发你能看到多少幅画.
Input
第一行有3个整数n,m,k(3<=n,m<=1000,1<=k<=min(m*m,100000) ).
接下来有n行每行m个字符,每个字符为'.'或者'*'.
紧接着k行,每行两个整数xi,yi.
Output
对于k个询问,输出相应的答案.
Examples
Input
5 6 3
******
*..*.*
******
*....*
******
2 2
2 5
4 3
Output
6
4
10
Input
4 4 1
****
*..*
*.**
****
3 2
Output
8
思路
1:可以看到多少幅画可以转换为记录有几面墙,类似于走迷宫的问题。
2:DFS,记录每一次"碰壁",直至与定义的空位相连的所有空位"."的四个方向全部遍历,跳出循环,输出结果。
AC的代码:
#include<iostream>
#define MAXN 1005
using namespace std;
char maze[MAXN][MAXN];
int n,m,k;
int vis[MAXN][MAXN];
int ans[100005];//记录墙的面数
int cnt = 0;
int d[4][2]={{0, 1},{1, 0},{0, -1},{-1, 0}};
void dfs(int x,int y)
{
vis[x][y] = cnt;
for(int i=0; i < 4; i++)
{
int nx = x + d[i][0];
int ny = y + d[i][1];
if(maze[nx][ny] == '*')
ans[cnt]++;
if(maze[nx][ny] == '.' && vis[nx][ny] == 0)
dfs(nx,ny);
}
return;
}
int main(){
cin >> n >> m >> k;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
cin >> maze[i][j];
}
}
while(k--)
{
int x,y;
cin >> x >> y;
if(vis[x][y])
cout << ans[vis[x][y]] << endl;
else
{
cnt++;
dfs(x,y);
cout << ans[cnt] << endl;
}
}
return 0;
}