class Solution {
public:
void setZeroes(vector<vector<int> > &mat) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (mat.size() == 0) return;
int r = mat.size();
int c = mat[0].size();
bool isVerticalZeros = false;
bool isHorizontalZeros = false;
if (mat[0][0] == 0)
{
isVerticalZeros = true;
isHorizontalZeros = true;
}
else
{
for (int i = 1; i < r; ++i)
{
if (mat[i][0] == 0)
{
isVerticalZeros = true;
break;
}
}
for (int j = 1; j < c; ++j)
{
if (mat[0][j] == 0)
{
isHorizontalZeros = true;
break;
}
}
}
for (int i = 1; i < r; ++i)
{
for (int j = 1; j < c; ++j)
{
if (mat[i][j] == 0)
{
mat[i][0] = 0;
mat[0][j] = 0;
}
}
}
for (int i = 1; i < r; ++i)
{
for (int j = 1; j < c; ++j)
{
if (mat[i][0] == 0)
{
mat[i][j] = 0;
}
}
}
for (int j = 1; j < c; ++j)
{
for (int i = 1; i < r; ++i)
{
if (mat[0][j] == 0)
{
mat[i][j] = 0;
}
}
}
if (isHorizontalZeros)
{
for (int j = 0; j < c; ++j)
{
mat[0][j] = 0;
}
}
if (isVerticalZeros)
{
for (int i = 0; i < r; ++i)
{
mat[i][0] = 0;
}
}
}
};
[Leetcode] Set Matrix Zeroes
最新推荐文章于 2024-08-16 09:55:14 发布