Set Matrix Zeros

Question:

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

Solution:

 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int>>& matrix) {
 4     int m=matrix.size();
 5     int n=matrix[0].size();
 6     vector<int> a;
 7     for(int i=0;i<matrix.size();i++)
 8         for(int j=0;j<matrix[i].size();j++)
 9             a.push_back(matrix[i][j]);
10     vector<int> b(a);
11     vector<int>::iterator iter=b.begin();
12     for(int i=0;i<a.size();i++)
13     {
14         if(0==a[i])
15         {
16             for(int j=0;j<n;j++)
17             {
18                 *(iter+(i/n)*n+j)=0;
19             }
20             for(int k=0;k<m;k++)
21             {
22                 *(iter+k*n+i%n)=0;
23             }
24         }
25     }
26     vector< vector<int> >matrix_temp;
27     vector<int> p;
28     for(int i=0;i<b.size();i++)
29     {    
30         p.push_back(b[i]);        
31         if(i%n==n-1)
32         {
33             matrix_temp.push_back(p);
34             p.erase(p.begin(),p.end());
35         }        
36     }
37     matrix =matrix_temp;    
38     }
39 };

Set Matrix Zeros_第1张图片

你可能感兴趣的:(Matrix)