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?

Solution: Use first row and column as auxiliary spaces instead of newly allocating ones.

 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int> > &matrix) {
 4         if(matrix.empty()) return;
 5         int R = matrix.size();
 6         int C = matrix[0].size();
 7         bool firstRowZero = false;
 8         bool firstColZero = false;
 9         
10         for(int j = 0; j < C; j++) {
11             if(matrix[0][j] == 0) {
12                 firstRowZero = true;
13                 break;
14             }
15         }
16         
17         for(int i = 0; i < R; i++) {
18             if(matrix[i][0] == 0) {
19                 firstColZero = true;
20                 break;
21             }
22         }
23         
24         for(int i = 1; i < R; i++) {
25             for(int j = 1; j < C; j++) {
26                 if(matrix[i][j] == 0) {
27                     matrix[i][0] = 0;
28                     matrix[0][j] = 0;
29                 }
30             }
31         }
32         
33         for(int i = 1; i < R; i++)
34             if(matrix[i][0] == 0)
35                 for(int j = 1; j < C; j++)
36                     matrix[i][j] = 0;
37         
38         for(int j = 1; j < C; j++)
39             if(matrix[0][j] == 0)
40                 for(int i = 1; i < R; i++)
41                     matrix[i][j] = 0;
42                     
43         if(firstRowZero)
44             for(int j = 0; j < C; j++)
45                 matrix[0][j] = 0;
46                 
47         if(firstColZero)
48             for(int i = 0; i < R; i++)
49                 matrix[i][0] = 0;
50     }
51 };

 

posted @ 2014-04-08 04:26  beehard  阅读(114)  评论(0编辑  收藏  举报