0, its entire row and column are set to 0.
Problem
You are given anm × n integer matrix. If an element in the matrix is 0, set its entire row and column to 0.
The modification must be done in-place.
Example(s)
Consider the following example(s) to understand the expected input and output.Input
matrix = [ [1,1,1], [1,0,1], [1,1,1] ]
Output
[ [1,0,1], [0,0,0], [1,0,1] ]
Since matrix[1][1] is 0, its entire row and column are set to 0.
Solution
This problem can be solved using the first row and first column as markers, allowing us to achieveO(1) extra space.
The main challenge is that if we immediately set a row or column to
0 while scanning the matrix, we may create new zeroes that were not present in the original matrix. Those newly created zeroes could incorrectly cause additional rows and columns to be set to zero.
Instead, we use the first row and first column to record which rows and columns originally contained a zero.
For every zero at
matrix[i][j], we mark its row using matrix[i][0] = 0 and its column using matrix[0][j] = 0.
Because the first row and first column are being used as markers, we separately remember whether they originally contained a zero.
After marking, we traverse the inner part of the matrix and set a cell to zero if its corresponding row or column has been marked.
Finally, we process the first row and first column themselves.
class Solution {
public void setZeroes(int[][] matrix) {
int firstColumn = 1;
int firstRow = 1;
int row = matrix.length;
int column = matrix[0].length;
// Check if first column contains zero
for (int i = 0; i < row; i++) {
if (matrix[i][0] == 0) {
firstColumn = 0;
}
}
// Check if first row contains zero
for (int j = 0; j < column; j++) {
if (matrix[0][j] == 0) {
firstRow = 0;
}
}
// Use first row and first column as markers
for (int i = 1; i < row; i++) {
for (int j = 1; j < column; j++) {
if (matrix[i][j] == 0) {
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
// Set matrix cells using markers
for (int i = 1; i < row; i++) {
for (int j = 1; j < column; j++) {
if (matrix[0][j] == 0 || matrix[i][0] == 0) {
matrix[i][j] = 0;
}
}
}
// Set first column
if (firstColumn == 0) {
for (int i = 0; i < row; i++) {
matrix[i][0] = 0;
}
}
// Set first row
if (firstRow == 0) {
for (int j = 0; j < column; j++) {
matrix[0][j] = 0;
}
}
}
}
Complexity
The matrix is traversed a constant number of times, resulting inO(n × m) time complexity, and only a constant number of variables is used apart from the matrix itself, resulting in O(1) extra space.
Comments
No comments yet. Ask a question or share what helped.