Medium
https://leetcode.com/problems/01-matrix/
BFS
Learn More →
use DP twice
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<vector<int>> dirs = {{0,-1},{-1,0},{0,1},{1,0}};
queue<pair<int, int>> q;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(mat[i][j] == 0)
{
q.push({i,j});
}
else
{
mat[i][j] = INT_MAX;
}
}
}
while(!q.empty())
{
auto t = q.front();
q.pop();
for(auto dir:dirs)
{
int x = t.first + dir[0], y = t.second + dir[1];
if(x < 0|| x >= m || y < 0 || y >= n || mat[x][y] <= mat[t.first][t.second] + 1)continue;
mat[x][y] = mat[t.first][t.second] + 1;
q.push({x,y});
}
}
return mat;
}
};
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int rows = matrix.size();
if (rows == 0)
return matrix;
int cols = matrix[0].size();
vector<vector<int>> dist(rows, vector<int> (cols, INT_MAX - 100000));
//First pass: check for left and top
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == 0) {
dist[i][j] = 0;
} else {
if (i > 0)
dist[i][j] = min(dist[i][j], dist[i - 1][j] + 1);
if (j > 0)
dist[i][j] = min(dist[i][j], dist[i][j - 1] + 1);
}
}
}
//Second pass: check for bottom and right
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 0; j--) {
if (i < rows - 1)
dist[i][j] = min(dist[i][j], dist[i + 1][j] + 1);
if (j < cols - 1)
dist[i][j] = min(dist[i][j], dist[i][j + 1] + 1);
}
}
return dist;
}
};
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up