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所在的行和列全都置為truefor(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的置為0for(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();}}
}