Java Solution - Easy to understand


#1

Comment body goes here. here

public static void setZeroes(ArrayList<ArrayList<Integer>> a) {
    if (a == null || a.size() == 0) {
        return;
    }

    final int M = a.size();
    final int N = a.get(0).size();

    boolean[] rowHasZero = new boolean[M];
    boolean[] columnHasZero = new boolean[N];

    // Find if any column/row has a Zero
    for (int rowNumber = 0; rowNumber < M; rowNumber++) {
        ArrayList<Integer> row = a.get(rowNumber);
        for (int colNumber = 0; colNumber < N; colNumber++) {
            int cellNumber = row.get(colNumber);
            if (cellNumber == 0) {
                rowHasZero[rowNumber] = true;
                columnHasZero[colNumber] = true;
            }
        }
    }

    // Update Rows to Zero
    for (int rowNumber = 0; rowNumber < M; rowNumber++) {
        if (rowHasZero[rowNumber]) {
            for (int i = 0; i < N; i++) {
                a.get(rowNumber).set(i, 0);
            }
        }
    }

    // Update columns to Zero
    for (int columnNumber = 0; columnNumber < N; columnNumber++) {
        if (columnHasZero[columnNumber]) {
            for (int i = 0; i < M; i++) {
                a.get(i).set(columnNumber, 0);
            }
        }
    }
}