[Leetcode]Set Matrix Zeroes

来源:互联网 发布:万国数据事件 编辑:程序博客网 时间:2024/05/22 17:14

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

第0行储存有0的column,如果row有0,在检查完row后将整行设为0

public class Solution {    public void setZeroes(int[][] matrix) {        int nrows = matrix.length;        int ncolumns = matrix[0].length;        boolean firstRowHasZero = false;        for(int i = 0; i < ncolumns; i++){            if(matrix[0][i] == 0){                firstRowHasZero = true;                break;            }        }                for(int i = 1; i< nrows; i++){            boolean rowHasZero = false;            for(int j = 0; j < ncolumns; j++){                if(matrix[i][j] == 0){                    matrix[0][j] = 0;                    rowHasZero = true;                }            }                        if(rowHasZero){                for(int j = 0; j < ncolumns; j++){                    matrix[i][j] = 0;                }            }        }                for(int i = 0; i < ncolumns; i++){            if(matrix[0][i] == 0){                for(int j = 1; j < nrows; j++){                    matrix[j][i] = 0;                }            }        }                if(firstRowHasZero){            for(int j = 0; j < ncolumns; j++){                matrix[0][j] = 0;            }        }            }}


0 0