Use the first 0 I find


  • 0
    B
    public void setZeroes(int[][] matrix) {
        int zeroI = -1;
        int zeroJ = -1;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == 0) {
                    if (zeroI == -1) { //not set yet
                        zeroI = i;
                        zeroJ = j;
                    } else {
                        matrix[i][zeroJ] = 0;
                        matrix[zeroI][j] = 0;
                    }
                }
            }
        }
        
        if (zeroI == -1) return;
        
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (i != zeroI && j != zeroJ && (matrix[i][zeroJ] == 0 || matrix[zeroI][j] == 0)) {
                    matrix[i][j] = 0;
                }
            }
        }
        
        for (int i = 0; i < matrix.length; i++) {
            matrix[i][zeroJ] = 0;
        }
        
        for (int j = 0; j < matrix[0].length; j++) {
            matrix[zeroI][j] = 0;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.