leetcode记录《零矩阵》
编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例 1:
输入:
[
[1,1,1],
[1,0,1],
[1,1,1]
]
输出:
[
[1,0,1],
[0,0,0],
[1,0,1]
]
/**
* @Description 零矩阵
* @Author messi
* @Date 2021/11/18 16:46
*/
public class test_02zero {
public static void main(String[] args) {
int[][] nums = {{0,1,2,0},{3,4,5,2},{1,3,1,5}};
int[][] nums1 = {{1,1,1},{1,0,1},{1,1,1}};
setZeroes1(nums1);
System.out.println(">>>>>>>>");
int[][] num11 = new int[4][4];
boolean[][] booleans = new boolean[4][4];
for (int i = 0;i<booleans.length;i++){
for (int j = 0;j<booleans[i].length;j++){
System.out.print(booleans[i][j]+"\t");
}
System.out.println();
}
}
/**
* 比较麻烦,主要是因为int类型里面默认值都是0,造成第一行,第一列始终都是0,采取赋值-1,比较慢108ms;
* @param matrix
*/
public static void setZeroes1(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
int[] row = new int[m];
for (int i = 0;i<row.length;i++){
row[i] = -1;
}
int[] col = new int[n];
for (int i = 0;i<col.length;i++){
col[i] = -1;
}
for (int i = 0;i<matrix.length;i++){
for (int j = 0;j<matrix[i].length;j++){
if (matrix[i][j] == 0){
row[i] = i;
col[j] = j;
}
}
}
for (int i = 0;i<row.length;i++){
if (row[i]!=-1){
for (int j= 0;j<n;j++){
matrix[row[i]][j] = 0;
}
}
}
for (int i = 0;i<col.length;i++){
if (col[i]!=-1){
for (int j= 0;j<m;j++){
matrix[j][col[i]] = 0;
}
}
}
for (int i = 0;i<matrix.length;i++){
for (int j = 0;j<matrix[i].length;j++){
System.out.print(matrix[i][j]+"\t");
}
System.out.println();
}
}
[添加链接描述](https://leetcode-cn.com/leetbook/read/array-and-string/ciekh/)
}