【LeetCode & 剑指offer刷题】矩阵题4:Set Matrix Zeroes

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

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.
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]
]
Follow up:
  • 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?

C++
 
//将矩阵中为0的元素其整行整列均置为0,要求in-place解决
//方法:第一次扫描,用首行首列存储状态,第二次扫描,根据这些状态把相应位置置0
//O(mn),O(1)
class Solution
{
public:
    void setZeroes(vector<vector<int>>& a)
    {
        int rows = a.size();
        int cols = a[0].size();
        bool fr = false; //用于表示首行是否存在0元素的标识变量
        bool fc = false;
       
        for(int i = 0; i<rows; i++)
        {
            for(int j = 0; j<cols; j++)
            {
                if(a[i][j] == 0)
                {
                    a[i][0] = a[0][j] = 0; //当某个元素为0时,将行首和列首元素置0
                    if(i == 0) fr = true; //第一行有0元素
                    if(j == 0) fc = true; //第一列有0元素
                }
            }
        }
       
        for(int i = 1; i<rows; i++) //从a11开始扫描,以免破坏首行首列存储信息
        {
            for(int j = 1; j<cols; j++)
            {
                if(a[i][0] == 0 || a[0][j] == 0) a[i][j] = 0;
            }
        }
       
        if(fr)
        {
            for(int j = 0; j<cols;j++) a[0][j] = 0; //将第一行置0
        }
        if(fc)
        {
            for(int i = 0; i<rows; i++) a[i][0] = 0; //将第一列置0
        }
       
    }
};
 
 

 

posted @ 2019-01-05 16:21  wikiwen  阅读(296)  评论(0编辑  收藏