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 发布
本文介绍了一个高效的算法,用于将包含0元素的矩阵中对应行和列的所有元素置为0。通过使用矩阵的第一行和第一列作为标记空间,该算法能在O(1)额外空间复杂度下完成任务。
708

被折叠的 条评论
为什么被折叠?



