Monday 19 September 2016

Set Matrix Zeroes (leetcode)

Problem: Set Matrix Zeroes
Given a m x n matrix, if an element is 0, set its entire row and column to 0.

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        
        int row = matrix.size();
        int col = matrix[0].size();
        
        bool row0[row], col0[col];
        fill_n(row0, row, true);
        fill_n(col0, col, true);
        
        for(int i=0;i<row;i++)
            for(int j=0;j<col;j++)
                if(matrix[i][j]==0)
                    row0[i]=col0[j]=false;
        for(int i=0;i<row;i++)
            if(!row0[i])
                for(int j=0;j<col;j++)
                    matrix[i][j]=0;
        for(int i=0;i<col;i++)
            if(!col0[i])
                for(int j=0;j<row;j++)
                    matrix[j][i]=0;
        return;
    }
};

No comments:

Post a Comment