1.7

来源:互联网 发布:win7怎么查看网络凭据 编辑:程序博客网 时间:2024/04/29 14:31

Topic: Write an algorithm such that if an element in an M*N matrix is 0, its entire row and column are set to 0.

// 注意点1:不能看到一个0,马上把那一行那一列都设为0,这样遍历的话,整个矩阵会全为0.

// 方法1:第一次遍历找到0的位置,标记在新开的matrix里;第二次遍历置0 (do a second pass).  SpaceO(M*N)

// 方法2:第一次遍历找到0的位置,把行号和列号标记在两个boolean array里;第二次遍历置0.

// 方法3To make more efficient, use a bit vector instead of a Boolean array.

public class CC1_1 {public static void SetZero(int [][] matrix){    boolean[] row = new boolean[matrix.length];    boolean[] column = new boolean[matrix[0].length];    for( int i = 0; i <matrix.length; i++ ){        for( int j = 0; j < matrix[0].length; j++ ){            if( matrix[i][j] == 0 ){                row[i] = true;                            column[j] = true;            }        }    }    for( int i = 0; i < matrix.length; i++ ){    for(int j=0; j<matrix[0].length;j++){        if(row[i]||column[j])          matrix[i][j] = 0;            }        }    }public static void print(int[][] matrix) {int n = matrix.length;for(int i = 0; i < n; i++) {for(int j = 0; j < n; j++) {System.out.print(matrix[i][j]);System.out.print(' ');}System.out.println();}}public static void main(String[] args) {int[][] matrix = {{1, 2, 3, 4},{5, 0, 7, 8},{9, 10, 0, 12},{13, 14, 15, 16}};SetZero(matrix);print(matrix);}}
//结果1 0 0 4 0 0 0 0 0 0 0 0 13 0 0 16