[Leetcode] 73. Set Matrix Zeroes

来源:互联网 发布:java工程师累不累 编辑:程序博客网 时间:2024/05/17 04:03

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;        int col = matrix[0].length;        boolean rowRecord = false;        boolean colRecord = false;        for(int i = 0; i < row; i++){            if(matrix[i][0] == 0){                rowRecord = true;                break;            }        }        for(int j = 0; j < col; j++){            if(matrix[0][j] == 0){                colRecord = true;                break;            }        }        for(int i = 1; i < row; i++){            for(int j = 1; j < col; j++){                if(matrix[i][j] == 0){                    matrix[i][0] = 0;                    matrix[0][j] = 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;                }            }        }        if(rowRecord){            for(int i = 0; i < row; i++){                matrix[i][0] = 0;            }        }        if(colRecord){            for(int i = 0; i < col; i++){                matrix[0][i] = 0;            }                   }    }}


0 0
原创粉丝点击