问题是将矩阵中所有0所在的行与列全部置0.
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
Example 1:
Input: [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ]Example 2:
Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ]
难点在于不能边遍历边置0,而是应当将遍历到的0保存起来,第二遍再进行置0,方法是用其它的值进行代替。
代码为:
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int INF = 1000000;
int M = matrix.size();
int N = matrix[0].size();//每行的列数都是相同的
//col表示列,row表示行
for(int i = 0; i < M; i++)
{
for(int j = 0; j < N; j++)
{
if(matrix[i][j] == 0)
{
matrix[i][j] = INF;
}
}
}
for(int i = 0; i < M; i++)
{
for(int j = 0; j < N; j++)
{
if(matrix[i][j] == INF)
{
for(int p = 0; p < M; p++)
{
if(matrix[p][j] != INF)
matrix[p][j] = 0;
}
for(int q = 0; q < N; q++)
{
if(matrix[i][q] != INF)
matrix[i][q] = 0;
}
matrix[i][j] = 0;
}
}
}
}
};