leetcode542 01 Matrix
Posted 王宜鸣
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode542 01 Matrix相关的知识,希望对你有一定的参考价值。
思路:
多个起点的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 };
以上是关于leetcode542 01 Matrix的主要内容,如果未能解决你的问题,请参考以下文章