Problem
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
Output:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
Input:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
Output:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
Follow up:
- A straight forward solution using O(mn) space is probably a bad idea.
- A simple improvement uses O(m + n) space, but still not the best solution.
- Could you devise a constant space solution?
Solution
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
var m = matrix.length;
var n = (matrix[0] || []).length;
for (var i = 0; i < m; i++) {
for (var j = 0; j < n; j++) {
if (matrix[i][j] === 0) {
left(i, j, m, n, matrix);
right(i, j, m, n, matrix);
up(i, j, m, n, matrix);
down(i, j, m, n, matrix);
} else if (matrix[i][j] === '#') {
matrix[i][j] = 0;
}
}
}
};
var left = function (i, j, m, n, matrix) {
for (var k = j - 1; k >= 0; k--) {
matrix[i][k] = 0;
}
};
var right = function (i, j, m, n, matrix) {
for (var k = j + 1; k < n; k++) {
matrix[i][k] = matrix[i][k] === 0 ? 0 : '#';
}
};
var up = function (i, j, m, n, matrix) {
for (var k = i - 1; k >= 0; k--) {
matrix[k][j] = 0;
}
};
var down = function (i, j, m, n, matrix) {
for (var k = i + 1; k < m; k++) {
matrix[k][j] = matrix[k][j] === 0 ? 0 : '#';
}
};
Explain:
把没遍历的 1
设置为 0
会影响之后的判断,先设置为 #
,再改回来。
Complexity:
- Time complexity : O(m*n).
- Space complexity : O(1).