Java Solution AC in-place


  • 0
    A
    public void setZeroes(final int[][] matrix) {
            if (matrix.length == 0 || matrix[0].length == 0) {
                return;
            }
    
            int rows = matrix.length, columns = matrix[0].length;
    
            boolean firstRowHasZero = false;
            for (int column = 0; column < columns; column++) {
                if (matrix[0][column] == 0) {
                    firstRowHasZero = true;
                    break;
                }
            }
    
            boolean firstColumnHasZero = false;
            for (int row = 0; row < rows; row++) {
                if (matrix[row][0] == 0) {
                    firstColumnHasZero = true;
                    break;
                }
            }
    
            for (int row = 1; row < rows; row++) {
                for (int column = 1; column < columns; column++) {
                    if (matrix[row][column] == 0) {
                        matrix[row][0] = 0;
                        matrix[0][column] = 0;
                    }
                }
            }
    
            for (int row = 1; row < rows; row++) {
                if (matrix[row][0] == 0) {
                    clearRow(matrix, row, columns);
                }
            }
    
            for (int column = 1; column < columns; column++) {
                if (matrix[0][column] == 0) {
                    clearColumn(matrix, column, rows);
                }
            }
    
            if (firstRowHasZero) {
                clearRow(matrix, 0, columns);
            }
    
            if (firstColumnHasZero) {
                clearColumn(matrix, 0, rows);
            }
        }
    
        private void clearColumn(final int[][] matrix, final int column, final int rows) {
            for (int row = 0; row < rows; row++) {
                matrix[row][column] = 0;
            }
        }
    
        private void clearRow(final int[][] matrix, final int row, final int columns) {
            for (int column = 0; column < columns; column++) {
                matrix[row][column] = 0;
            }
        }
    

Log in to reply
 

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