LeetCode OJ:Set Matrix Zeroes

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?


class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        int m = matrix.size();  
        if(0 == m) return;  
        int n = matrix[0].size();  
  
        // 按行遍历,把包含0的行中的所有非0数用UINT_MAX标记  
        for (int i=0; i<m; ++i)  
        {  
            for (int j=0; j<n; ++j)  
            {  
                if (matrix[i][j] == 0)  
                {  
                    for (j=0; j<n; ++j)  
                    {  
                        if (matrix[i][j] != 0)  
                            matrix[i][j] = UINT_MAX;  
                    }  
                    break;  
                }  
            }  
        }  
  
        // 按列遍历,把包含0的列中的所有数字置为0,并把UINT_MAX的元素置为0  
        for (int i=0; i<n; ++i)  
        {  
            for (int j=0; j<m; ++j)  
            {  
                if (matrix[j][i] == 0)  
                {  
                    for (j=0; j<m; ++j)  
                        matrix[j][i] = 0;  
                    break;  
                }  
  
                if(matrix[j][i] == UINT_MAX)  
                    matrix[j][i] = 0;  
            }  
        }  
    }
};


你可能感兴趣的:(LeetCode)