542. 01 Matrix
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
[[0,0,0],
[0,1,0],
[0,0,0]]
Output:
[[0,0,0],
[0,1,0],
[0,0,0]]
Example 2:
Input:
[[0,0,0],
[0,1,0],
[1,1,1]]
Output:
[[0,0,0],
[0,1,0],
[1,2,1]]
Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- The cells are adjacent in only four directions: up, down, left and right.
官方题解:https://leetcode.com/problems/01-matrix/solution/
方法1:bfs
思路:
将每一个1都设置成INT_MAX,这样matrix本身就可以当作visited来用。同时将每一个0一起推进queue完成initialization,0本身正好也代表了到最近0点的距离。在遍历过程中凡是遇到matrix上记录的最短距离值小于新的距离的话,可以直接跳过,否则改写成新的最短距离。
Complexity
Time complexity: O(mn)
Space complexity: O(mn)
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
queue<vector<int>> q;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j]) matrix[i][j] = INT_MAX;
else {
q.push({i, j});
}
}
}
while (!q.empty()) {
auto top = q.front();
q.pop();
for (auto dir: dirs) {
int x = top[0] + dir[0];
int y = top[1] + dir[1];
if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size() || matrix[x][y] <= matrix[top[0]][top[1]] + 1) continue;
matrix[x][y] = matrix[top[0]][top[1]] + 1;
q.push({x, y});
}
}
return matrix;
}
};
方法2: dynamic programming
思路:
相当于dp的一种解法,一个matrix[i][j] = 1的点离零点的最近距离只能继承自它上下左右四个方向。那么可以左上->右下扫一遍先找一遍可能的最短距离,再右下->左上扫一遍,一定能求出结果。
dp: 每个点到最近0的距离
initialization:INT_MAX - 1 for matrix[i][j] = 1, 0 for matrix[i][j] = 0。这是因为每一次从左上继承下来的时候,需要比较两者较小值 + 1,并和当前值比较。但左上角有可能就是还没有遇到过0,两个继承值都是INT_MAX,为了防止overflow必须初始化成INT_MAX - 1。那么从右下到左上呢?由于题目规定了至少存在一个0,所以第二次遍历所取到的最小值一定不会是INT_MAX,不用担心overflow的问题。
transfer: 左上->右下dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1); dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1); 右下->左上dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1); dp[i][j] = min(dp[i][j], dp[i][j +1] + 1); 注意防 边界溢出。
return:dp
Complexity
Time complexity: O(mn)
Space complexity: O(mn)
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> dp(m, vector<int> (n, INT_MAX - 1));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) dp[i][j] = 0;
else {
if (i > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1);
if (j > 0) dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1);
}
}
}
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
if (i < m - 1) dp[i][j] = min(dp[i][j], dp[i + 1][j] + 1);
if (j < n - 1) dp[i][j] = min(dp[i][j], dp[i][j + 1] + 1);
}
}
return dp;
}
};