leetcode76set-matrix-zeroes

题目描述

给定一个m*n的矩阵,如果有一个元素是0,就把该元素所在的行和列上的元素全置为0,要求使用原地算法。
拓展:
你的算法有使用额外的空间吗?
一种比较直接的算法是利用O(m,n)的空间,但是这不是一个好的解法
使用简单的改进可以在O(m+n)的空间解决这个问题,但是还不是最佳的解法
你能在常量级的空间复杂度内解决这个问题吗?

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

Follow up: Did you use extra space?
A straight forward solution using O(m n) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        const int row=matrix.size();
        const int col=matrix[0].size();
        bool row_flag=false,col_flag=false;
        
        for (int i=0;i<row ;i++)
            if (0==matrix [i][0])
            {
                col_flag=true;
                break;
            }
            
        
        for (int i=0;i<col;i++)
            if (0==matrix[0][i])
            {
                row_flag=true;
                break;
            }
        
        for (int i=1;i<row;i++)
            for (int j=1;j<col;j++)
                if (0==matrix[i][j]){
                    
                
                    matrix[i][0]=0;
                    matrix[0][j]=0;
                }
                
            
            
        
        for (int i=1;i<row;i++){
            for (int j=1;j<col;j++){
                if (0==matrix[i][0] || matrix [0][j]==0)
                    matrix[i][j]=0;
            }
        }
        if (row_flag)
            for (int i=0;i<col;i++)
                matrix[0][i]=0;
        if (col_flag)
            for (int i=0;i<row;i++)
                matrix[i][0]=0;
        
    }
};

posted on 2020-07-31 07:29  滚雪球效应  阅读(135)  评论(0编辑  收藏  举报