Java算法–第四章–多维数组和矩阵(2)题目:0所在得行列清零
如果矩阵中某个元素为0,则将其所在的行和列清零
1 2 3 4
5 6 0 8
9 0 11 12
13 14 15 16
变为:
1 0 0 4
0 0 0 0
0 0 0 0
13 0 0 16
代码:
package matrix;
import java.util.Arrays;
public class ClearZeroInArr {
public static void main(String[] args) {
int[][] matrix = {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 0, 10 },
{ 11, 12, 13, 14, 15 },
{ 16, 0, 18, 19, 20 },
{ 21, 22, 23, 24, 25 },
};
clearzero(matrix);
for (int i = 0; i < matrix.length; i++) {
for(int j = 0;j <matrix[0].length;j++) {
System.out.print(matrix[i][j]+"\t");
}
System.out.println();
}
}
static void clearzero(int[][] matrix) {
int M = matrix.length;
int N = matrix[0].length;
//记录哪些行出现0
int[] rowRecord = new int[M];
//记录哪些列出现0
int[] colRecord = new int[N];
for(int i = 0;i < M;i++) {
for(int j = 0;j < N;j++) {
if(matrix[i][j] == 0) {
rowRecord[i] = 1;
colRecord[j] = 1;
}
}
}
for(int row = 0;row <M;row++) {
for(int col = 0;col < N;col++) {
if(rowRecord[row] ==1 || colRecord[col] == 1) {
matrix[row][col] =0;
}
}
}
}
}
输出:
1 0 3 0 5
0 0 0 0 0
11 0 13 0 15
0 0 0 0 0
21 0 23 0 25