fork download
  1. // HoaiNam
  2. #include <bits/stdc++.h>
  3. #define endl "\n"
  4. #define int long long
  5. #define all(x) x.begin(), x.end()
  6. #define NAME ""
  7. using namespace std;
  8.  
  9. const int N = 1e3 + 1;
  10. const int INF = 1e9;
  11. const int mod = 1e9 + 7;
  12.  
  13. int dx[] = { -1, 0, 1, 0};
  14. int dy[] = {0, 1, 0, -1};
  15.  
  16. int n, m, dist[N][N];
  17. char A[N][N];
  18.  
  19. void bfs() {
  20. queue<pair<int, int>> q;
  21. for (int i = 1; i <= n; ++i)
  22. for (int j = 1; j <= m; ++j) {
  23. dist[i][j] = INF;
  24. }
  25. for (int i = 1; i <= n; ++i)
  26. for (int j = 1; j <= m; ++j) {
  27. if (A[i][j] == '1') {
  28. q.push({i, j});
  29. dist[i][j] = 0;
  30. }
  31. }
  32.  
  33. while (!q.empty()) {
  34. auto [u, v] = q.front();
  35. q.pop();
  36. for (int i = 0; i < 4; ++i) {
  37. int x = u + dx[i];
  38. int y = v + dy[i];
  39. if (x >= 1 && x <= n && y >= 1 && y <= m && dist[x][y] > dist[u][v] + 1) {
  40. dist[x][y] = dist[u][v] + 1;
  41. q.push({x, y});
  42. }
  43. }
  44. }
  45. }
  46.  
  47. signed main() {
  48. ios::sync_with_stdio(false);
  49. cin.tie(nullptr);
  50.  
  51. if (fopen(NAME".INP", "r")) {
  52. freopen(NAME".INP", "r", stdin);
  53. freopen(NAME".OUT", "w", stdout);
  54. }
  55.  
  56. cin >> n >> m;
  57.  
  58. for (int i = 1; i <= n; ++i) {
  59. for (int j = 1; j <= m; ++j) {
  60. cin >> A[i][j];
  61. }
  62. }
  63.  
  64. bfs();
  65.  
  66. int ans = 0;
  67. for (int i = 1; i <= n; ++i) {
  68. for (int j = 1; j <= m; ++j) {
  69. if (dist[i][j] != INF) ans = max(ans, dist[i][j]);
  70. }
  71. }
  72. cout << ans;
  73.  
  74. // HoaiNam
  75. }
  76.  
Success #stdin #stdout 0.01s 5260KB
stdin
Standard input is empty
stdout
Standard output is empty