跳至主要内容

542. 01 Matrix

  • BFS
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>> seen;

for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (mat[i][j] == 0)
{
q.push({i, j, 0});
seen.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 || seen.count({new_i, new_j})) continue;
q.push({new_i, new_j, dist});
seen.insert({new_i, new_j});
res[new_i][new_j] = dist;
}
}
return res;
}
};
  • T: O(MN)O(M \cdot N)
  • S: O(MN)O(M \cdot N)