D. Igor In the Museum(简单DFS)

先预处理出每一个联通块的答案,然后查询时就可以O(1)出答案;

/* ***********************************************
Author        :xdlove
Created Time  :2015年11月15日 星期日 16时47分40秒
File Name     :xdlove/codeforces/Educational_Codeforces_Round_1/D/D.cpp
************************************************ */

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>

using namespace std;


#define REP_ab(i,a,b) for(int i = a; i <= b; i++)
#define REP(i, n) for(int i = 0; i < n; i++)
#define REP_1(i,n) for(int i = 1; i <= n; i++)
#define DEP(i,n) for(int i = n - 1; i >= 0; i--)
#define DEP_N(i,n) for(int i = n; i >= 1; i--)
#define CPY(A,B) memcpy(A,B,sizeof(B))
#define MEM(A) memset(A,0,sizeof(A))
#define MEM_1(A) memset(A,-1,sizeof(A))
#define MEM_INF(A) memset(A,0x3f,sizeof(A))
#define MEM_INFLL(A) memset(A,0x3f3f,sizeof(A))
#define mid (((l + r) >> 1))
#define lson l, mid, u << 1
#define rson mid + 1, r, u << 1 | 1
#define ls (u << 1)
#define rs (u << 1 | 1)


typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3f;
const int MAXN = 1e3 + 5;
const int MAXM = MAXN;
const int mod = 1e9 + 7;
char s[MAXN][MAXN];
int n,m,k;
int vis[MAXN][MAXN];
int res[MAXN * MAXN];
int dx[] = {
    0,0,-1,1
};
int dy[] = {
    -1,1,0,0
};
int id;

bool check(int x,int y)
{
    if(x < 0 || y < 0 || x >= n || y >= m || vis[x][y]) return false;
    return true;
}

int dfs(int x,int y)
{
    vis[x][y] = id;
    int cnt = 0;
    for(int i = 0; i < 4; i++)
    {
        int nx = dx[i] + x;
        int ny = dy[i] + y;
        if(check(nx,ny))
        {
            if(s[nx][ny] != '.') cnt++;
            else cnt += dfs(nx,ny);
        }
    }
    return cnt;
}

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    cin>>n>>m>>k;
    REP(i,n) scanf("%s",s[i]);
    id = 1;
    MEM(vis);
    REP(i,n) 
    {
        REP(j,m)
        {
            if(s[i][j] == '.' && !vis[i][j])
            {
                res[id] = dfs(i,j);
                id++;
            }
        }
    }
    while(k--)
    {
        int x,y;
        scanf("%d %d",&x,&y);
        x--,y--;
        printf("%d\n",res[vis[x][y]]);
    }
    return 0;
}


你可能感兴趣的:(DFS)