topic
Write an algorithm to clear the row and column where an element in an M × N matrix is 0.
Example 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
Example 2:
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
analyze
In the matrix, if you encounter 0
a value of , press the cross to clear the value of the row and column. Think about how to achieve it.
First of all, the given matrix is a square matrix, and the width and height are not necessarily the same. So pay attention to the width and height when defining temporary array storage.
The first thing that comes to mind is 遍历矩阵
that if you encounter something 0
that will be 当前行
converted 当前列
to data 0
, this method is possible, but you should pay attention to the modified row and column 不能参与后面的数据判断
, otherwise the modified value and the original data will be generated 混淆
. So if you use this method, you need to mark the rows and columns as modified values.
If the marking and value refreshing are performed in a cycle, it is a bit confusing and difficult to sort out, so it will be divided 标记
into 值刷新
two steps. First define the sum of 宽高两个数组
as , and then traverse the two arrays, and if it is, clear the row and column data of the corresponding matrix.0
列
行
true
true
code show as below:
public void setZeroes(int[][] matrix) {
boolean row[] = new boolean[matrix.length];
boolean vertical[] = new boolean[matrix[0].length];
for(int i = 0; i < matrix.length;i++){
int now[] = matrix[i];
for (int j = 0; j < now.length; j++) {
if (now[j] == 0){
row[i] = true;
vertical[j] = true;
}
}
}
for (int i = 0; i < row.length; i++) {
int now[] = new int[matrix[0].length];
if (row[i]){
matrix[i] = now;
}
}
for (int i = 0; i < vertical.length; i++) {
if (vertical[i]){
for (int j = 0; j < matrix.length; j++) {
matrix[j][i] = 0;
}
}
}
}
Results of the: