[LeetCode] Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

click to show follow up.

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?

解题思路:
这题挺容易出问题,要考虑到如果遇到matrix[i][j]就清零第i行,第j列所有元素,会导致只要有一个零元则整个矩阵被清零。如下做法中,将零元信息记录在了第一行,第一列。但是这里有一个特殊的matrix[0][0],如果它是零,要考虑到它到底是记录的行有0,还是列有0,还是行列同时有0。
 
class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if(matrix.size() == 0) return;
    int type = 0;
    for(int i = 0;i < matrix.size();i++)
    {
        for(int j = 0;j < matrix[0].size();j++)
        {
            if(matrix[i][j] == 0)
            {
                matrix[i][0] = 0;
                matrix[0][j] = 0;
                if(i == 0)
                {
                    if(type == 0) type = 1;
                    else if(type == 2) type = 3;
                    else continue;
                }
                if(j == 0)
                {
                    if(type == 0) type = 2;
                    else if(type == 1) type = 3;
                    else continue;
                }
            }
        }
    }
    for(int i = 1;i < matrix.size();i++)
    {
        if(matrix[i][0] == 0)
            for(int j = 0;j < matrix[0].size();j++)
                matrix[i][j] = 0;
    }
    for(int j = 1;j < matrix[0].size();j++)
    {
        if(matrix[0][j] == 0)
            for(int i = 0;i < matrix.size();i++)
                matrix[i][j] = 0;
    }
    
    if(type == 1 || type == 3)
        for(int j = 0;j < matrix[0].size();j++)
            matrix[0][j] = 0;
    if(type == 2 || type == 3)
        for(int i = 0;i < matrix.size();i++)
            matrix[i][0] = 0;
}
};

 

posted @ 2013-11-11 20:02  xchangcheng  阅读(120)  评论(0编辑  收藏  举报