Advertisement
MaxObznyi

BFS - C

May 14th, 2022
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. const int N = 1001;
  8. const int INF = 1e9 + 1;
  9. const int dx[8] = {1, -1, 0, 0, 1, 1, -1, -1};
  10. const int dy[8] = {0, 0, 1, -1, 1, -1, 1, -1};
  11.  
  12. int n, m, dist[N][N];
  13. char a[N][N];
  14.  
  15. int main()
  16. {
  17. cin >> n >> m;
  18. for (int i = 0; i < n; i++)
  19. for (int j = 0; j < m; j++) {
  20. cin >> a[i][j];
  21. dist[i][j] = INF;
  22. }
  23. queue<pair<int, int>> q;
  24. int k;
  25. cin >> k;
  26. for (int i = 0; i < k; i++) {
  27. int x, y;
  28. cin >> x >> y;
  29. x--;
  30. y--;
  31. dist[x][y] = 0;
  32. q.push({x, y});
  33. }
  34.  
  35. while (!q.empty()) {
  36. auto [x, y] = q.front();
  37. q.pop();
  38. ///check neighbours
  39. for (int d = 0; d < 8; d++) {
  40. int ax = x + dx[d];
  41. int ay = y + dy[d];
  42. if (ax >= 0 && ax < n && ay >= 0 && ay < m && a[ax][ay] == '.' && dist[ax][ay] == INF) {
  43. dist[ax][ay] = dist[x][y] + 1;
  44. q.push({ax, ay});
  45. }
  46. }
  47. }
  48.  
  49. int mx = -1;
  50. for (int i = 0; i < n; i++)
  51. for (int j = 0; j < m; j++)
  52. if (dist[i][j] != INF)
  53. mx = max(mx, dist[i][j]);
  54.  
  55. vector<pair<int, int>> ans;
  56. for (int i = 0; i < n; i++)
  57. for (int j = 0; j < m; j++)
  58. if (dist[i][j] == mx)
  59. ans.push_back({i, j});
  60. cout << ans.size() << "\n";
  61. for (auto [x, y] : ans)
  62. cout << x + 1 << ' ' << y + 1 << "\n";
  63.  
  64. return 0;
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement