思路:
宽搜,多个起点。
实现:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <queue> 5 #include <cstring> 6 using namespace std; 7 8 const int INF = 0x3f3f3f3f; 9 10 char a[805][805]; 11 int n, m, d[805][805]; 12 bool vis[805][805]; 13 int dx[4] = { 1, 0, -1, 0 }; 14 int dy[4] = { 0, 1, 0, -1 }; 15 16 struct node 17 { 18 int x, y; 19 }; 20 void solve() 21 { 22 queue<node> q; 23 for (int i = 0; i < n; i++) 24 { 25 for (int j = 0; j < m; j++) 26 { 27 if (a[i][j] == '0') 28 { 29 vis[i][j] = true; 30 q.push(node{i, j}); 31 } 32 } 33 } 34 while (!q.empty()) 35 { 36 node tmp = q.front(); 37 q.pop(); 38 for (int i = 0; i < 4; i++) 39 { 40 int nx = tmp.x + dx[i]; 41 int ny = tmp.y + dy[i]; 42 if (nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny] && a[nx][ny] == '1') 43 { 44 vis[nx][ny] = true; 45 d[nx][ny] = d[tmp.x][tmp.y] + 1; 46 q.push(node{nx, ny}); 47 } 48 } 49 } 50 } 51 52 int main() 53 { 54 cin >> n >> m; 55 for (int i = 0; i < n; i++) 56 { 57 for (int j = 0; j < m; j++) 58 { 59 cin >> a[i][j]; 60 } 61 } 62 solve(); 63 for (int i = 0; i < n; i++) 64 { 65 for (int j = 0; j < m; j++) 66 { 67 cout << d[i][j] << " "; 68 } 69 puts(""); 70 } 71 return 0; 72 }