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.
Example
Given a matrix
[
[1,2],
[0,3]
],
return
[
[0,2],
[0,0]
]
Challenge
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
Analysis:
We are going to use two sets to save all the column numbers and row numbers whose cells need to be set to 0. This will cost O(m + n) space.
Another approach is from: http://fisherlei.blogspot.com/2013/01/leetcode-set-matrix-zeroes.html
1.先确定第一行和第一列是否需要清零
2.扫描剩下的矩阵元素,如果遇到了0,就将对应的第一行和第一列上的元素赋值为0
3.根据第一行和第一列的信息,已经可以讲剩下的矩阵元素赋值为结果所需的值了
4.根据1中确定的状态,处理第一行和第一列。
2.扫描剩下的矩阵元素,如果遇到了0,就将对应的第一行和第一列上的元素赋值为0
3.根据第一行和第一列的信息,已经可以讲剩下的矩阵元素赋值为结果所需的值了
4.根据1中确定的状态,处理第一行和第一列。
1 class Solution { 2 public void setZeroes(int[][] matrix) { 3 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; 4 5 boolean firstRowZero = false, firstColumnZero = false; 6 7 // set first row and column zero or not 8 for (int i = 0; i < matrix.length; i++) { 9 if (matrix[i][0] == 0) { 10 firstColumnZero = true; 11 break; 12 } 13 } 14 15 for (int i = 0; i < matrix[0].length; i++) { 16 if (matrix[0][i] == 0) { 17 firstRowZero = true; 18 break; 19 } 20 } 21 22 // mark zeros on first row and column 23 for (int i = 1; i < matrix.length; i++) { 24 for (int j = 1; j < matrix[0].length; j++) { 25 if (matrix[i][j] == 0) { 26 matrix[i][0] = 0; 27 matrix[0][j] = 0; 28 } 29 } 30 } 31 32 // use mark to set elements 33 for (int i = 1; i < matrix.length; i++) { 34 for (int j = 1; j < matrix[0].length; j++) { 35 if (matrix[i][0] == 0 || matrix[0][j] == 0) { 36 matrix[i][j] = 0; 37 } 38 } 39 } 40 41 // set first column and row 42 if (firstColumnZero) { 43 for (int i = 0; i < matrix.length; i++) 44 matrix[i][0] = 0; 45 } 46 47 if (firstRowZero) { 48 for (int i = 0; i < matrix[0].length; i++) 49 matrix[0][i] = 0; 50 } 51 } 52 }