#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int x,y;
vector<vector<char>>c;
vector<vector<bool>>vis;
int dx[] = {0,1,0,-1};
int dy[] = {-1,0,1,0};
vector<vector<pair<int,int>>>parent;
pair<int,int> find(pair<int,int>g){
if(parent[g.first][g.second]==g)
return g;
return find(parent[g.first][g.second]);
}
void Union(int i,int j,int ii,int jj){
parent[ii][jj]= find({i,j});
}
void fill(){
for(int i = 0;i < x;i++)
for(int j = 0 ; j < y;j++)
parent[i][j] = {i,j};
}
bool isvalid(int xx,int yy){
return xx >= 0 and yy >= 0 and xx < x and yy < y;
}
int dfs(int xx,int yy){
if(c[xx][yy] == '*') return 1;
vis[xx][yy] = 1;
int cnt = 0;
for(int i = 0 ; i < 4;i++){
if(isvalid(xx + dx[i],yy + dy[i]) && !vis[xx + dx[i]][yy + dy[i]]){
Union(xx,yy,xx + dx[i],yy + dy[i]);
cnt += dfs(xx + dx[i],yy + dy[i]);
}
}
return cnt;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt" , "r", stdin );
freopen("out.txt", "w", stdout);
#endif
int m; cin>>x>>y>>m;
c.resize(x,vector<char>(y));
parent.resize(x,vector<pair<int,int>>(y));
vis.resize(x,vector<bool>(y));
fill();
map<pair<int,int>,int>mp;
for(int i = 0 ; i < x;i++)
for(int j = 0 ; j < y;j++)
cin>>c[i][j];
for(int i = 0 ; i < m;i++){
int a,b; cin>>a>>b;
a--; b--;
pair<int,int> it = find({a,b});
if(mp.find(it) != mp.end()) cout<<mp[it]<<'\n';
else{
mp[{it.first,it.second}] = dfs(a,b);
cout<<mp[{it.first,it.second}]<<'\n';
}
}
}
1609A - Divide and Multiply | 149B - Martian Clock |
205A - Little Elephant and Rozdil | 1609B - William the Vigilant |
978B - File Name | 1426B - Symmetric Matrix |
732B - Cormen --- The Best Friend Of a Man | 1369A - FashionabLee |
1474B - Different Divisors | 1632B - Roof Construction |
388A - Fox and Box Accumulation | 451A - Game With Sticks |
768A - Oath of the Night's Watch | 156C - Cipher |
545D - Queue | 459B - Pashmak and Flowers |
1538A - Stone Game | 1454C - Sequence Transformation |
165B - Burning Midnight Oil | 17A - Noldbach problem |
1350A - Orac and Factors | 1373A - Donut Shops |
26A - Almost Prime | 1656E - Equal Tree Sums |
1656B - Subtract Operation | 1656A - Good Pairs |
1367A - Short Substrings | 87A - Trains |
664A - Complicated GCD | 1635D - Infinite Set |