1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
   | #include <iostream> #include <cstring> #include <queue>
  using namespace std;
  typedef pair<int,int> PII;
  const int N = 1010, INF = 0x3f3f3f3f;
  int A[N][N], B[N][N]; int n, m; queue<PII> q;
  int main() {     memset(B, 0x3f, sizeof B);     cin >> n >> m;     for (int i = 0; i < n; ++ i)     {         string s;         cin >> s;         for (int j = 0; j < s.size(); ++ j)          {             A[i][j] = s[j] - '0';             if (A[i][j] == 1) q.push({i, j}), B[i][j] = 0;         }     }
      int xy[][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
      while (!q.empty())     {         auto t = q.front();          q.pop();         int dx = t.first, dy = t.second;
          for (int i = 0; i < 4; ++ i)         {             int x = dx + xy[i][0], y = dy + xy[i][1];             if (x >= 0 && x < n && y >= 0 && y < m && B[x][y] == INF)             {                 B[x][y] = B[dx][dy] + 1;                 q.push({x, y});             }         }     }
 
      for (int i = 0; i < n; ++ i)     {         for (int j = 0; j < m; ++ j)             printf("%d ", B[i][j]);         puts("");     }
      return 0; }
   |