C - O(1) space, O(mn) time, 44ms


  • 0
    G
    void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) {
        if (!matrix || (matrixRowSize <= 0) || (matrixColSize<= 0)) return;
        const int NCOLS = matrixColSize;
        int i, j, m, n, row_0_zero = 0, row_zero;
        for (i = 0; i < matrixRowSize; i++) {
            row_zero = 0;
            for (j = 0; j < NCOLS; j++) {
                if (matrix[i][j] == 0) {
                    matrix[0][j] = 0;
                    if (i == 0) {
                        if (!row_0_zero) row_0_zero = 1;
                    } else {
                        if (!row_zero) row_zero = 1;
                    }
                }
            }
            if (row_zero) {
                for (n = 0; n < NCOLS; n++) if (matrix[i][n]) matrix[i][n] = 0;
            }
        }
        for (j = 0; j < NCOLS; j++) {
            if (matrix[0][j] == 0) {
                for (m = 1; m < matrixRowSize; m++) if (matrix[m][j]) matrix[m][j] = 0;
            }
        }
        if (row_0_zero) {
            for (n = 0; n < NCOLS; n++) if (matrix[0][n]) matrix[0][n] = 0;
        }
    }

Log in to reply
 

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