代码改变世界

leetcode - Set Matrix Zeroes

2013-11-02 19:49  张汉生  阅读(161)  评论(0)    收藏  举报

 

 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int> > &matrix) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         if (matrix.size()<=0 || matrix[0].size()<=0)
 7             return;
 8         int i, j, m=matrix.size(),n=matrix[0].size();
 9         bool lastZero = false, curZero = false;
10         for (i=0; i<m; i++){
11             curZero = false;
12             for (j=0; j<n; j++){
13                 if (matrix[i][j]==0){
14                     for (int k=i-1; k>=0; k--)
15                         matrix[k][j] = 0;
16                     curZero = true;
17                 }
18                 else if (i>0 && matrix[i-1][j]==0)
19                     matrix[i][j] = 0;
20             }
21             if (i>0 && lastZero){
22                 for (j=0; j<n; j++)
23                     matrix[i-1][j] = 0;
24             }
25             lastZero = curZero;
26         }
27         if (lastZero){
28             for (j=0; j<n; j++)
29                 matrix[m-1][j] =0;
30         }
31         return;
32     }
33 };