542. 01 Matrix
BFS
/*
* @lc app=leetcode id=542 lang=cpp
*
* [542] 01 Matrix
*
* https://leetcode.com/problems/01-matrix/description/
*
* algorithms
* Medium (49.81%)
* Likes: 9993
* Dislikes: 434
* Total Accepted: 696.7K
* Total Submissions: 1.4M
* Testcase Example: '[[0,0,0],[0,1,0],[0,0,0]]'
*
* Given an m x n binary matrix mat, return the distance of the nearest 0 for
* each cell.
*
* The distance between two cells sharing a common edge is 1.
*
*
* Example 1:
*
*
* Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
* Output: [[0,0,0],[0,1,0],[0,0,0]]
*
*
* Example 2:
*
*
* Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
* Output: [[0,0,0],[0,1,0],[1,2,1]]
*
*
*
* Constraints:
*
*
* m == mat.length
* n == mat[i].length
* 1 <= m, n <= 10^4
* 1 <= m * n <= 10^4
* mat[i][j] is either 0 or 1.
* There is at least one 0 in mat.
*
*
*
* Note: This question is the same as 1765:
* https://leetcode.com/problems/map-of-highest-peak/
*
*/
// @lc code=start
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat)
{
int m = mat.size(), n = mat[0].size();
queue<vector<int>> q;
set<pair<int, int>> used;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (mat[i][j] == 0)
{
q.push({i, j, 0});
used.insert({i, j});
}
}
}
vector<vector<int>> res = mat;
vector<vector<int>> directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
while (!q.empty())
{
auto node = q.front(); q.pop();
for (const auto& dir : directions)
{
int new_i = node[0] + dir[0];
int new_j = node[1] + dir[1];
int dist = node[2] + 1;
if (new_i < 0 || new_j < 0 || new_i >= m || new_j >= n || used.count({new_i, new_j})) continue;
q.push({new_i, new_j, dist});
used.insert({new_i, new_j});
res[new_i][new_j] = dist;
}
}
return res;
}
};
// @lc code=end
- T:
- S: