Sunday, February 9, 2014

Leetcode: 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:

We could use two arrays to mark the rows and cols that have a zero in it, but to use constant space we can use the first row and column (or any other). As afterwards we do not know if this row and col had at the beginning a zero or not, we save this information before modifying them.

public class Solution {
    public void setZeroes(int[][] matrix) {
        boolean firstRowHasZero = false;
        boolean firstColHasZero = false;
        if(matrix.length==0 || matrix[0].length ==0)
            return;
        for (int column = 0; column < matrix[0].length; column++)
        {
            if(matrix[0][column]==0)
            {
                firstRowHasZero = true;
                break;
            }
        }
        
        for (int row = 0; row < matrix.length; row++)
        {
            if(matrix[row][0]==0)
            {
                firstColHasZero = true;
                break;
            }
        }
        
        for (int column = 0; column < matrix[0].length; column++)
        {
            for (int row=1; row < matrix.length; row++)
            {
                if(matrix[row][column]==0)
                {
                    matrix[0][column] = 0;
                    matrix[row][0] = 0;
                }
            }
        }

        for (int column = 1; column < matrix[0].length; column++)
        {
            for (int row=1; row < matrix.length; row++)
            {
                if(matrix[0][column] == 0 || matrix[row][0] == 0)
                    matrix[row][column] = 0;
            }
        }
        
        if(firstColHasZero)
        {
            for (int row = 0; row < matrix.length; row++)
                matrix[row][0]=0;
        }
        
        if(firstRowHasZero)
        {
            for(int col = 0; col < matrix[0].length; col++)
                matrix[0][col]=0;
        }
    }
}

No comments :

Post a Comment