思路:
多个起点的bfs。
实现:
1 class Solution 2 { 3 public: 4 vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) 5 { 6 int n = matrix.size(), m = matrix[0].size(); 7 vector<vector<int>> vis(n, vector<int>(m, 0)); 8 vector<vector<int>> d(n, vector<int>(m, 0x3f3f3f3f)); 9 queue<pair<int, int>> q; 10 int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1}; 11 for (int i = 0; i < n; i++) 12 { 13 for (int j = 0; j < m; j++) 14 { 15 if (matrix[i][j] == 0) 16 { 17 q.push(pair<int, int>(i, j)); 18 vis[i][j] = 1; 19 d[i][j] = 0; 20 } 21 } 22 } 23 while (!q.empty()) 24 { 25 pair<int, int> tmp = q.front(); 26 q.pop(); 27 int x = tmp.first, y = tmp.second; 28 for (int i = 0; i < 4; i++) 29 { 30 int nx = x + dx[i], ny = y + dy[i]; 31 if (nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny]) 32 { 33 vis[nx][ny] = 1; 34 d[nx][ny] = d[x][y] + 1; 35 q.push(pair<int, int>(nx, ny)); 36 } 37 } 38 } 39 return d; 40 } 41 };
原文地址:https://www.cnblogs.com/wangyiming/p/9819665.html
时间: 2024-11-13 01:33:38