Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
这道题的关键是不能直接进行set 0 操作,会把原来的数据冲掉,最后导致整个矩阵都是0,应该保存0的位置。只需要m+n个buffer就行了。
void reset(int ** matrix, int m, int n)
{
bool row[m] = {false};
bool col[n] = {false};
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (matrix[i][j] == 0)
{
row[i] = true;
col[j] = true;
}
}
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (row[i] == 0 || col[j] == 0)
{
matrix[i][j] = 0;
}
}
}
}