wayetan
12/30/2013 - 12:49 AM

Set Matrix Zeroes

Set Matrix Zeroes

/**
 * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
 * Did you use extra space?
 * A straight forward solution using O(mn) space is probably a bad idea.
 * A simple improvement uses O(m + n) space, but still not the best solution.
 * Could you devise a constant space solution?
 */
 public class Solution {
    public void setZeroes(int[][] matrix) {
        boolean frtRow = false, frtCol = false;
        int rows = matrix.length;
        int cols = matrix[0].length;
        // first make sure if the first row and first column need to be set 0 or not.
        for(int i = 0; i < rows; i++){
            if(matrix[i][0] == 0){
                frtCol = true;
                break;
            }
        }
        for(int i = 0; i < cols; i++){
            if(matrix[0][i] == 0){
                frtRow = true;
                break;
            }
        }
        // scan the rest of the matrix, and mark the first row and first column in the matrix with 0s.
        for(int i = 1; i < rows; i++){
            for(int j = 1; j < cols; j++){
                if(matrix[i][j] == 0){
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        // set 0s.
        for(int i = 1; i < rows; i++){
            for(int j = 1; j < cols; j++){
                if(matrix[i][0] == 0 || matrix[0][j] == 0)
                    matrix[i][j] = 0;
            }
        }
        if(frtRow){
            for(int i = 0; i< cols; i++){
                matrix[0][i] = 0;
            }
        }
        if(frtCol){
            for(int i = 0; i< rows; i++){
                matrix[i][0] = 0;
            }
        }
    }
}