Saturday, 11 April 2015

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

public void setZeroes(int[][] matrix) {
    int rows = matrix.length;
    int cols = matrix[0].length;
    boolean[] rowzero = new boolean[rows];
    boolean[] colzero = new boolean[cols];
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            if (matrix[r][c] == 0) {
                rowzero[r] = true;
                colzero[c] = true;
            }
        }
    }
    for (int r = 0; r < rows; r++) {
        if (rowzero[r]) {
            for (int c = 0; c < cols; c++) {
                matrix[r][c] = 0;
            }
        }
    }
    for (int c = 0; c < cols; c++) {
        if (colzero[c]) {
            for (int r = 0; r < rows; r++) {
                matrix[r][c] = 0;
            }
        }
    }
}


  • Variable naming. flagArr is a matrix and not an (1 diemensional) array. But it would be more helpful to name it to what it is used for rather than what it is. How about zerosFound? i and j I would either name as x and y or col and row.
  • Spacing. It's not wrong to have a bit of more space in your lines. Use spaces around < and = and before { etc. Here's what parts of your code looks like when I press Ctrl + Shift + F in Eclipse (which is a key shortcut for auto formatting).
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (matrix[i][j] == 0) {
                flagArr[i][j] = true;
            }
        }
    }



No comments:

Post a Comment