Sunday, May 20, 2018

[2018-Interview] Set Matrix Zeroes

Original question: https://leetcode.com/problems/set-matrix-zeroes/description/

My answer:



class Solution {
    public void setZeroes(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        boolean originColumn = false; // if true, zero out the 0th column, used to avoid case where [i][0] is 0, while [0][0] is not
        boolean originRow = false; // if true, zero out the 0th row, used to avoid case where [0][j] is 0, while [0][0] is not
        if (matrix[0][0] == 0) {
            originColumn = true;
            originRow = true;
        }
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j ++) {
                // mark the index for 0s at row 0, and column 0
                if (matrix[i][j] == 0) {
                        matrix[i][0] = 0;
                        matrix[0][j] = 0;
                        if (i == 0) {
                            originRow = true;
                        }
                        if (j == 0) {
                            originColumn = true;
                        }
                }
            }
        }
        for (int i = 1; i < matrix.length; i++) {
            if (matrix[i][0] == 0) {
                for (int j = 1; j < matrix[0].length; j ++) {
                    matrix[i][j] = 0;
                }
            }
        }
        for (int j = 1; j < matrix[0].length; j ++) {
            if (matrix[0][j] == 0) {
                for (int i = 1; i < matrix.length; i ++) {
                    matrix[i][j] = 0;
                }
            }
        }
        if (matrix[0][0] == 0) {
                if (originRow) {
                    for (int j = 1; j < matrix[0].length; j ++) {
                        matrix[0][j] = 0;
                    }                    
                }
                if (originColumn) {
                    for (int i = 1; i < matrix.length; i ++) {
                        matrix[i][0] = 0;
                    }                    
                }

        }
    }
}

No comments:

Post a Comment