Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:
Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix)
{
if (matrix.empty()) return;
int M = matrix.size();
int N = matrix[0].size();
bool zeroV = 0; bool zeroH = 0;
for (int i = 0; i < M; i++)
if (matrix[i][0] == 0)
{
zeroV = 1;
break;
}
for (int j = 0; j < N; j++)
if (matrix[0][j] == 0)
{
zeroH = 1;
break;
}
for (int i = 1; i < M; i++)
for (int j = 1; j < N; j++)
if (0 == matrix[i][j])
{
matrix[i][0] = 0;
matrix[0][j] = 0;
}
for (int i = 1; i < M; i++)
if (0 == matrix[i][0])
for (int j = 1; j < N; j++)
matrix[i][j] = 0;
for (int i = 1; i < N; i++)
if (0 == matrix[0][i])
for (int j = 1; j < M; j++)
matrix[j][i] = 0;
if (1 == zeroH)
for (int i = 0; i < N; i++)
matrix[0][i] = 0;
if (1 == zeroV)
for (int i = 0; i < M; i++)
matrix[i][0] = 0;
}
};