题意:在一个m*n的矩阵中matrix中,若matrix[i][j]==0 ,就将第i行和第j列的元素都设为0;
思路一:遍历,直观解法,设置两个数组,分别记录行和列的boolean值。
代码:
package SetMatrixZero;
public class SetMatrixZero {
public void SetZero(int [][]matrix){
int m = matrix.length;
int n = matrix[0].length;
if(m == 0 || n == 0) return;
boolean []arr1 = new boolean [m+1];
boolean []arr2 =new boolean [n+1];
for(int i = 0 ; i < m ; i++){
for(int j = 0 ; j < n ; j++){
if(matrix[i][j] == 0)
arr1[i] = arr2[j] = true;
}
}
for(int i = 0 ; i < m ; i++){
if(arr1[i]){
for(int j = 0 ;j<n;j++){
matrix[i][j] = 0;
}
}
}
for(int j = 0 ; j < n ; j++){
if(arr2[j]){
for(int i = 0 ; i< m ; i++){
matrix[i][j] = 0;
}
}
}
}
public static void main(String[] args) {
SetMatrixZero smz = new SetMatrixZero();
int num = 0;
int [][]temp = {{1,2,3,9},{4,0,0,2},{0,2,3,4},{2,2,3,0}};
for (int[] is : temp) {
for (int i : is) {
System.out.print(i+" ");
num++;
if((num)%temp.length == 0) System.out.println('\r');
}
}
System.out.println("\n"+"************");
smz.SetZero(temp);
for (int[] is : temp) {
for (int i : is) {
System.out.print(i+" ");
num++;
if((num)%temp.length == 0) System.out.println('\r');
}
}
}
}