1.题目描述
2.思路
(1)计算矩阵的行数
(2)计算矩阵的列数
(3)设计一个行列的bool数组
(4)遍历矩阵(二维数组),如果遇到元素0,则把元素0所在的行和列全都置为true
(5)再次遍历矩阵(二维数组),如果行数组为true把行数组置为0,如果列数组为true把列数组置为0.
注意点:
3.代码实现
public class H73 {
public void setZeroes(int[][] matrix) {
//1.计算矩阵的行数
int m=matrix.length;
//2.计算矩阵的列数
int n=matrix[0].length;
//3.设计一个行列的bool数组,boolean 是基本类型,默认值就是 false,不需要额外初始化。
//Java 中数组初始化默认值为 null,而不是 false。
//如果声明用Boolean,使用 row[i] == true 的时候,如果 row[i] 没被赋值过,就会变成 null == true,会抛出 NullPointerException。
boolean[] row=new boolean[m];
boolean[] col=new boolean[n];
//4.遍历矩阵(二维数组),如果遇到元素0,则把元素0所在的行和列全都置为true
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(matrix[i][j]==0)
{
row[i]=true;
col[j]=true;
}
}
}
//5.再次遍历矩阵(二维数组),如果行数组为true把行数组置为0,如果列数组为true把列数组置为0.也就是把矩阵中的行列置为true的置为0
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(row[i]==true||col[j]==true)
{
matrix[i][j]=0;
}
}
}
}
public static void main(String[] args)
{
H73 test08=new H73();
int[][] matrix={{1,1,1},{1,0,1},{1,1,1}};
test08.setZeroes(matrix);
for(int[] row:matrix)//先遍历一维数组,行数组
{
for(int value:row)//再遍历列数组
{
System.out.print(value+" ");
}
System.out.println();
}
}
}