Link: https://oj.leetcode.com/problems/set-matrix-zeroes/
我的思路:用第0列存储每一行是否有0。需要用第一行存储每一列是否有0吗?
我的代码:不正确。需要重做。//错误的原因是:m[0][3] = 5,在最后一个for loop时,被m[0][0]=0改写成0,使得最后一列都变成0.
Input:[[0,0,0,5],[4,3,1,4],[0,1,1,4],[1,2,1,3],[0,0,1,1]]
Output:[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
Expected:[[0,0,0,0],[0,0,0,4],[0,0,0,0],[0,0,0,3],[0,0,0,0]]
public class Solution {
public void setZeroes(int[][] matrix) {
for(int i = 0; i < matrix.length; i++){
for(int j = 1; j < matrix[0].length; j++){
if(matrix[i][j] == 0){
matrix[i][0] = 0;
break;
}
}
}
for(int j = 0; j < matrix[0].length; j++){
for(int i = 1; i < matrix.length; i++){
if(matrix[i][j] == 0){
matrix[0][j] = 0;
break;
}
}
}
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
if(matrix[i][0] == 0 || matrix[0][j] == 0){
matrix[i][j] = 0;
}
}
}
}
}
正确思路:
http://blog.csdn.net/linhuanmars/article/details/24066199
第一行和第一列,如果(n-1)*(n-1)矩阵有0,就把它的值赋成0(无论第一行或者第一列有没有0, 它最终也该是0),否则保留原值。然后根据第一行和第一列的记录对其他元素进行置0。最后再根据前面的两个标记来确定是不是要把第一行和第一列置0。
Time: O(m*n), Space: O(1)
public class Solution {
public void setZeroes(int[][] matrix) {
boolean firstRow = false;//if firstRow has 0, change to true
boolean firstCol = false;
for(int j = 0; j < matrix[0].length; j++){
if(matrix[0][j] == 0){
firstRow = true;
break;
}
}
for(int i = 0; i < matrix.length; i++){
if(matrix[i][0] == 0) {
firstCol = true;
break;
}
}
//use 1st row and 1st col to store the corresponding row and col's situation
for(int i = 1; i < matrix.length; i++){
for(int j = 1; j < matrix[0].length; j++){
if(matrix[i][j] == 0){
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
//set zeroes
for(int i = 1; i < matrix.length; i++){
for(int j = 1; j < matrix[0].length; j++){
if(matrix[i][0] == 0 || matrix[0][j] == 0){
matrix[i][j] = 0;
}
}
}
//set the 1st row and 1st col
if(firstRow){
for(int j = 0; j < matrix[0].length; j++){
matrix[0][j] = 0;
}
}
if(firstCol){
for(int i = 0; i < matrix.length; i++){
matrix[i][0] = 0;
}
}
}
}