073 Set Matrix Zeroes 矩阵置零

时间:2023-03-10 06:14:00
073 Set Matrix Zeroes 矩阵置零

给定一个 m x n 的矩阵,如果一个元素为 0 ,则将这个元素所在的行和列都置零。
你有没有使用额外的空间?
使用 O(mn) 的空间不是一个好的解决方案。
使用 O(m + n) 的空间有所改善,但仍不是最好的解决方案。
你能设计一个使用恒定空间的解决方案吗?
详见:https://leetcode.com/problems/set-matrix-zeroes/description/

Java实现:

class Solution {
public void setZeroes(int[][] matrix) {
int m=matrix.length;
int n=matrix[0].length;
boolean rowZero=false;
boolean colZero=false;
for(int j=0;j<n;++j){
if(matrix[0][j]==0){
rowZero=true;
}
}
for(int i=0;i<m;++i){
if(matrix[i][0]==0){
colZero=true;
}
}
for(int i=1;i<m;++i){
for(int j=1;j<n;++j){
if(matrix[i][j]==0){
matrix[i][0]=0;
matrix[0][j]=0;
}
}
}
for(int i=1;i<m;++i){
for(int j=1;j<n;++j){
if(matrix[i][0]==0||matrix[0][j]==0){
matrix[i][j]=0;
}
}
}
if(rowZero){
for(int j=0;j<n;++j){
matrix[0][j]=0;
}
}
if(colZero){
for(int i=0;i<m;++i){
matrix[i][0]=0;
}
}
}
}

参考:https://www.cnblogs.com/grandyang/p/4341590.html