上题:
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
题目的意思是有一个矩阵,如果矩阵某些元素等于0,则将该元素所在的行与列都赋值为0,约束是常熟空间。我在这题的思路是充分利用第一行与第一列,若某元素等于0,则将所在的第一行与第一列赋值为0。上代码:
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix)
{
int m = matrix.size();
int n = matrix[0].size();
bool row = false;
bool col = false;
for (int i = 0; i < m; i++)
{
if (matrix[i][0] == 0)
{
col = true;
break;
}
}
for (int i = 0; i < n; i++)
{
if (matrix[0][i] == 0)
{
row = true;
break;
}
}
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; j++)
{
if (matrix[i][j] == 0)
{
matrix[0][j] = 0;
matrix[i][0] = 0;
}
}
}
for (int i = 1; i < m; i++)
{
if (matrix[i][0] == 0)
{
for (int j = 0; j < n; j++)
{
matrix[i][j] = 0;
}
}
}
for (int i = 1; i < n; i++)
{
if (matrix[0][i] == 0)
{
for (int j = 0; j < m; j++)
{
matrix[j][i] = 0;
}
}
}
if(row)
{
for (int i = 0; i < n; i++)
{
matrix[0][i] = 0;
}
}
if (col)
{
for (int i = 0; i < m; i++)
{
matrix[i][0] = 0;
}
}
}
};