源题目

https://leetcode-cn.com/problems/01-matrix/

542. 01 矩阵

难度中等470
给定一个由 0 和 1 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。

示例 1:
广度/ 深度优先搜索--LeetCode 542. 01 矩阵 - 图1
输入:mat = [[0,0,0],[0,1,0],[0,0,0]] 输出:[[0,0,0],[0,1,0],[0,0,0]]
示例 2:
广度/ 深度优先搜索--LeetCode 542. 01 矩阵 - 图2
输入:mat = [[0,0,0],[0,1,0],[1,1,1]] 输出:[[0,0,0],[0,1,0],[1,2,1]]

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • mat[i][j] is either 0 or 1.
  • mat 中至少有一个 0

通过次数62,257
提交次数135,513

  1. class Solution {
  2. public:
  3. vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
  4. int m = matrix.size(), n = matrix[0].size();
  5. vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}};
  6. queue<pair<int, int>> q;
  7. for (int i = 0; i < m; ++i) {
  8. for (int j = 0; j < n; ++j) {
  9. if (matrix[i][j] == 0) q.push({i, j});
  10. else matrix[i][j] = INT_MAX;
  11. }
  12. }
  13. while (!q.empty()) {
  14. auto t = q.front(); q.pop();
  15. for (auto dir : dirs) {
  16. int x = t.first + dir[0], y = t.second + dir[1];
  17. if (x < 0 || x >= m || y < 0 || y >= n ||
  18. matrix[x][y] <= matrix[t.first][t.second]) continue;
  19. matrix[x][y] = matrix[t.first][t.second] + 1;
  20. q.push({x, y});
  21. }
  22. }
  23. return matrix;
  24. }
  25. };