Set Matrix Zeroes

Leave a comment

December 17, 2016 by oneOokay

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.


  1. 把第一行和第一列作为标记行和标记列
  2. 另外两个单独的boolean来标记第一行和第一列自身是否也为0
public class Solution {
    public void setZeroes(int[][] matrix) {
        if (matrix == null){
            return;
        }
        boolean firstRow = false;
        boolean firstCol = false;
        for (int i = 0; i < matrix.length; i ++){
            for (int j = 0; j < matrix[0].length; j ++){
                if (matrix[i][j] == 0) {
                    if (i == 0) firstRow = true;
                    if (j == 0) firstCol = true;
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        
        for (int i = 1; i < matrix.length; i ++){
            if (matrix[i][0] == 0){
                setZeroesForRow(matrix, i);
            }
        }
        
        for (int i = 1; i < matrix[0].length; i ++){
            if (matrix[0][i] == 0){
                setZeroesForCol(matrix, i);
            }
        }
        
        if (firstRow){
            setZeroesForRow(matrix, 0);
        }
        if (firstCol){
            setZeroesForCol(matrix, 0);
        }
    }
    
    private void setZeroesForRow(int[][] matrix, int rowNumber){
        for (int i = 0; i < matrix[0].length; i ++){
            matrix[rowNumber][i] = 0;
        }
    }
    
    private void setZeroesForCol(int[][] matrix, int colNumber){
        for (int i = 0; i < matrix.length; i ++){
            matrix[i][colNumber] = 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

%d bloggers like this: