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.

 
public class Solution {
    public void setZeroes(int[][] matrix) {
        int row = matrix.length; 
        if (row == 0) return; 
        int col = matrix[0].length; 
        //marker 
        boolean fr = false, fc = false; 
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(matrix[i][j] == 0) {
                    if(i == 0) fr = true;
                    if(j == 0) fc = true;
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        
        //change corresponding row/col to 0 
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0; 
                }
            }
        }
        //because the first row/col, need to use fc&fr to track their true status. 
        if (fr) {
            for (int j = 0; j < col; j++) {
                matrix[0][j] = 0; 
            }
        }
        if (fc) {
            for (int i = 0; i < row; i++) {
                matrix[i][0] = 0; 
            }
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s