leetcode73 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.

Follow up:

Did you use extra space?
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?

 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int>>& matrix) {
 4         int m=matrix.size();
 5         if(!m)
 6             return;
 7         int n=matrix[0].size();
 8         vector<int> mlist(m,0);
 9         vector<int> nlist(n,0);
10         int i,j;
11         for(i=0;i<m;i++)
12         {
13             for(j=0;j<n;j++)
14             {
15                 if(matrix[i][j]==0)
16                 {
17                     mlist[i]=1;
18                     nlist[j]=1;
19                 }
20             }
21         }
22         for(i=0;i<m;i++)
23         {
24             if(mlist[i]==1)
25             {
26                 for(j=0;j<n;j++)
27                 {
28                     matrix[i][j]=0;
29                 }
30             }
31         }
32         for(i=0;i<n;i++)
33         {
34             if(nlist[i]==1)
35             {
36                 for(j=0;j<m;j++)
37                 {
38                     matrix[j][i]=0;
39                 }
40             }
41         }
42     }
43 };
View Code

 

posted @ 2016-01-06 15:54  西小贝  阅读(135)  评论(0编辑  收藏  举报