码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 73. Set Matrix Zeroes

时间:2018-08-30 00:19:27      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:cto   amp   record   col   ||   false   tor   set   mat   

利用matrix的第一行和第一列来记录,第二遍扫描时再根据记录的信息把matrix的元素置0。

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int m=matrix.size(), n=m==0?0:matrix[0].size();
        bool clear_first_row=false;
        bool clear_first_col=false;
        
        // use the first row and the first col to record
        for (int i=0;i<m;++i){
            for (int j=0;j<n;++j){
                if (matrix[i][j]==0){
                    if (i==0) clear_first_row=true;
                    if (j==0) clear_first_col=true;
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        
        for (int i=1;i<m;++i){
            for (int j=1;j<n;++j){
                if (matrix[0][j]==0 || matrix[i][0]==0)
                    matrix[i][j] = 0;
            }
        }
        
        if (clear_first_row){
            for (int j=0;j<n;++j)
                matrix[0][j] = 0;
        }
        if (clear_first_col){
            for (int i=0;i<m;++i)
                matrix[i][0] = 0;
        }
    }
};

 

LeetCode 73. Set Matrix Zeroes

标签:cto   amp   record   col   ||   false   tor   set   mat   

原文地址:https://www.cnblogs.com/hankunyan/p/9557418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!