CodeForces 598D 【dfs+技巧省时】

来源:互联网 发布:java iterator 将int 编辑:程序博客网 时间:2024/06/03 23:50
B - B
Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u
Submit Status Practice CodeForces 598D

Description

Igor is in the museum and he wants to see as many pictures as possible.

Museum can be represented as a rectangular field of n × m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.

At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.

For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.

Input

First line of the input contains three integers nm and k (3 ≤ n, m ≤ 1000, 1 ≤ k ≤ min(n·m, 100 000)) — the museum dimensions and the number of starting positions to process.

Each of the next n lines contains m symbols '.', '*' — the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.

Each of the last k lines contains two integers x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) — the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns — from left to right. It is guaranteed that all starting positions are empty cells.

Output

Print k integers — the maximum number of pictures, that Igor can see if he starts in corresponding position.

Sample Input

Input
5 6 3*******..*.********....*******2 22 54 3
Output
6410
Input
4 4 1*****..**.******3 2
Output
8
代码:
/*dfs+技巧!因为相邻的点(.)他们都有相同数目的外面的*,所以他们对应的编号相同,编号相同对应的输出的*的个数也就相等了,然后可以在递归的过程中对其的编号数组进行赋值,并且标记访问过了,这样下次遇到它就不会重新递归找*的个数了!节省了时间! 就这样把所有的.周围的*求出来,需要哪个就输出哪个就行了! */#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int n,m,k;char a[1005][1005];int vis[1005][1005];int time[1005][1005];int num[1000005];int dfs_clock;int sum;int dx[4]={0,1,-1,0};int dy[4]={1,0,0,-1};int judge(int x,int y){return x>=0&&x<n&&y>=0&&y<m;}void dfs(int x,int y){vis[x][y]=1;time[x][y]=dfs_clock;for(int i=0;i<4;i++){int next_x=x+dx[i];int next_y=y+dy[i];if(!judge(next_x,next_y)||vis[next_x][next_y])continue;if(a[next_x][next_y]=='*'){sum++;}else{dfs(next_x,next_y);}}}int main(){scanf("%d%d%d",&n,&m,&k);for(int i=0;i<n;i++){scanf("%s",a[i]);}dfs_clock=0;for(int i=0;i<n;i++){for(int j=0;j<m;j++){if(a[i][j]=='.'&&!vis[i][j]){dfs_clock++;sum=0;dfs(i,j);num[dfs_clock]=sum;}}}while(k--){int sx,sy;scanf("%d%d",&sx,&sy);printf("%d\n",num[time[sx-1][sy-1]]);}return 0;}


0 0
原创粉丝点击