Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
题解:因为题目要求原地算法,所以我们只能利用矩阵第一行和第一列存放置零信息。
代码如下:
1 public class Solution { 2 public void setZeroes(int[][] matrix) { 3 int m = matrix.length; 4 int n = matrix[0].length; 5 boolean first_column_zero = false; 6 boolean first_row_zero = false; 7 8 for(int i = 0;i < m;i ++){ 9 if(matrix[i][0] == 0) 10 first_column_zero =true; 11 } 12 for(int i = 0;i < n;i ++){ 13 if(matrix[0][i] == 0) 14 first_row_zero = true; 15 } 16 17 for(int i = 1;i < m;i++){ 18 for(int j = 1;j < n;j ++){ 19 if(matrix[i][j]== 0){ 20 matrix[i][0] = 0; 21 matrix[0][j]= 0; 22 } 23 } 24 } 25 26 for(int i = 1;i < m;i++){ 27 for(int j = 1;j < n;j ++){ 28 if(matrix[i][0] == 0 || matrix[0][j]== 0 ) 29 matrix[i][j]= 0; 30 } 31 } 32 33 if(first_column_zero){ 34 for(int i = 0;i < m;i ++) 35 matrix[i][0] = 0; 36 } 37 if(first_row_zero){ 38 for(int i = 0;i < n;i ++) 39 matrix[0][i] = 0; 40 } 41 } 42 }
【leetcode刷题笔记】Set Matrix Zeroes,布布扣,bubuko.com
【leetcode刷题笔记】Set Matrix Zeroes
原文地址:http://www.cnblogs.com/sunshineatnoon/p/3830216.html