Wednesday, January 7, 2015

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.

At the first glance, this seems very easy. However, I couldn't figure out why we need to first mark the first row and first column if  there is any 0 elements,  check the rest of the matrix and set those rows and columns to zeros, then set first row or first column to zero if they are marked. Now I know.

Consider a matrix like this:
In the end, we want a matrix like this: 

If we set zeros from the first row, after the first set, it will be like this: 
In the end, it will be: 

A disaster... :O

So, the correct way is to mark the first row and first column if there is any 0. 
Check the rest of the matrix, if matrix[i][j] = 0, set matrix[i][0] = 0 and matrix[0][j] = 0. 
Set row i and column j to zeros if matrix[i][0] = 0 or matrix[0][j] = 0.
Set first row and first column to zeros if they are marked. 







public void setZeroes(int[][] matrix) {
        if (matrix == null) 
            throw new NullPointerException("Null matrix!");
        if (matrix.length == 0)
            return;
        boolean firstRow = false;
        boolean firstCol = false;
        
        for (int i = 0; i < matrix.length; i++) {
            if (matrix[i][0] == 0) {
                firstCol = true;
                break;
            }
        }
        for (int j = 0; j < matrix[0].length; j++) {
            if (matrix[0][j] == 0) {
                firstRow = true;
                break;
            }
        }
        
        for (int i = 1; i < matrix.length; i++) {
            for (int j = 1; j < matrix[0].length; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        for (int i = 1; i < matrix.length; i++) {
            for (int j = 1; j < matrix[0].length; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0)
                    matrix[i][j] = 0;
            }
        }
        if(firstRow == true) {
            for (int j = 0; j < matrix[0].length; j++)
                matrix[0][j] = 0;
        }
        if (firstCol == true) {
            for (int i = 0; i < matrix.length; i++) 
                matrix[i][0] = 0;
        }
    }

No comments:

Post a Comment