分析:BFS,同一连通区域的周长一样,但查询过多会导致TLE,所以要将连通区域的答案储存,下次查询到该连通区域就可以直接得出结果
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 #include 14 #include 15 #include 16 const double PI = acos(-1.0);17 const int INF = 0x3f3f3f3f;18 const int NINF = -INF - 1;19 typedef long long ll;20 #define MOD 100000721 using namespace std;22 typedef pair P;23 char map[1005][1005];24 int n, m, ans, cnt;25 int x, y;26 int dx[4] = { 1, 0, -1, 0}, dy[4] = { 0, 1, 0, -1};27 int vis[1005][1005];28 int num[1000025];29 void bfs()30 {31 int i, j;32 queue q;33 q.push(P(x, y));34 cnt++;35 vis[x][y] = cnt;36 ans = 0;37 while (q.size())38 {39 P temp = q.front();40 q.pop();41 ans += 4;42 for (i=0; i < 4; ++i)43 {44 int nx = temp.first + dx[i];45 int ny = temp.second + dy[i];46 if (nx >= 0 && nx < n && ny >= 0 && ny < m)47 {48 if(map[nx][ny] == '.')49 {50 ans--;51 if(!vis[nx][ny])52 {53 q.push(P(nx, ny));54 vis[nx][ny] = cnt;55 }56 }57 }58 else59 ans--;60 }61 }62 num[cnt] = ans;63 cout << ans << endl;64 }65 66 int main()67 {68 int i, j, k;69 cin >> n >> m >> k;70 for (i = 0; i < n; ++i)71 cin >> map[i];72 memset(num, -1, sizeof(num));73 memset(vis, 0, sizeof(vis));74 cnt = 0;75 while (k--)76 {77 cin >> x >> y;78 x--, y--;79 if (vis[x][y] == 0)80 bfs();81 else82 cout << num[vis[x][y]] << endl;83 }84 return 0;85 }