fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int a[] = {0, 1, 0, -1};
  5. int b[] = {1, 0, -1, 0};
  6.  
  7. char piece[355][355];
  8. bool check[355][355];
  9. int P, Q, N;
  10.  
  11. int bfs(int x, int y) {
  12. queue<pair<int, int>> q;
  13. q.push({x, y});
  14. check[x][y] = true;
  15.  
  16. int pieces = 0;
  17.  
  18. while (!q.empty()) {
  19. tie(x, y) = q.front();
  20. q.pop();
  21.  
  22. for (int i = 0; i < 4; i++) {
  23. int nx = x + a[i];
  24. int ny = y + b[i];
  25.  
  26. if (nx < 0 || nx >= P || ny < 0 || ny >= Q) continue;
  27. if (piece[nx][ny] == '#') pieces++;
  28. else if (!check[nx][ny]) {
  29. q.push({nx, ny});
  30. check[nx][ny] = true;
  31. }
  32. }
  33. }
  34. return pieces;
  35. }
  36.  
  37. int main() {
  38. ios_base::sync_with_stdio(false);
  39. cin.tie(NULL);
  40.  
  41. cin >> P >> Q >> N;
  42. for (int i = 0; i < P; i++) {
  43. for (int j = 0; j < Q; j++) {
  44. cin >> piece[i][j];
  45. }
  46. }
  47.  
  48. while (N--) {
  49. memset(check, false, sizeof(check));
  50. int x, y;
  51. cin >> x >> y;
  52. cout << bfs(x - 1, y - 1) << "\n";
  53. }
  54.  
  55. return 0;
  56. }
  57.  
Success #stdin #stdout 0.01s 5420KB
stdin
5 5 3
#####
#..##
#..##
###.#
#####
2 2
3 3
4 4
stdout
8
8
4