Tuesday, February 11, 2014

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.
Solution:
First try: flag matrix.
Second try: use first row and first column to save 0s. check if it has zero or not first.



public class Solution {
    public void setZeroes(int[][] matrix) {
        int rowNum = matrix.length;
        int colNum = matrix[0].length;
        if(rowNum == 0 && colNum == 0) return;
        
        Boolean firstRowHasZero = false;
        Boolean firstColHasZero = false;
        for(int j = 0; j < colNum; j++){
            if(matrix[0][j] == 0){
                firstRowHasZero = true;
                break;
            } 
        }
        for(int i = 0; i < rowNum; i++){
            if(matrix[i][0] == 0){
                firstColHasZero = true;
                break;
            } 
        }
        
        for(int i = 1; i < rowNum; i++){
            for(int j = 1; j < colNum; j++){
                if(matrix[i][j] == 0){
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        for(int i = 1; i < rowNum; i++){
            for(int j = 1; j < colNum; j++){
                if(matrix[i][0] == 0 || matrix[0][j] == 0){
                    matrix[i][j] = 0;
                }
            }
        }
        
        
        if(firstColHasZero || firstRowHasZero) matrix[0][0] = 0;
        if(firstRowHasZero){
            for(int j = 1; j < colNum; j++){
                matrix[0][j] = 0;
            }
        }
        if(firstColHasZero){
            for(int i = 1; i < rowNum; i++){
                matrix[i][0] = 0;
            }
        }
        return;
    }
}

No comments:

Post a Comment