[Leetcode] 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.

如果不用额外空间的话,可以把第一行与第一列作为标记行与标记列,但是得先确定第一行与第一列本身要不要设为0。

 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int> > &matrix) {
 4         if (matrix.size() < 1) return;
 5         int row = matrix.size(), col = matrix[0].size();
 6         bool r0 = false, c0 = false;
 7         for (int i = 0; i < row; ++i) {
 8             if (matrix[i][0] == 0) {
 9                 c0 = true; break;
10             }
11         }
12         for (int j = 0; j < col; ++j) {
13             if (matrix[0][j] == 0) {
14                 r0 = true; break;
15             }
16         }
17         for (int i = 1; i < row; ++i) {
18             for (int j = 1; j < col; ++j) {
19                 matrix[i][0] = (matrix[i][j] == 0) ? 0 : matrix[i][0];
20                 matrix[0][j] = (matrix[i][j] == 0) ? 0 : matrix[0][j];
21             }   
22         }
23         for (int i = 1; i < row; ++i) {
24             for (int j = 1; j < col; ++j) {
25                  matrix[i][j] = (matrix[i][0] == 0) ? 0 : matrix[i][j];
26                  matrix[i][j] = (matrix[0][j] == 0) ? 0 : matrix[i][j];
27             }   
28         }
29         for (int i = 0; i < row && c0; ++i)  matrix[i][0] = 0;
30         for (int j = 0; j < col && r0; ++j)  matrix[0][j] = 0;
31     }
32 };

 

 

posted @ 2014-04-05 13:54  Eason Liu  阅读(214)  评论(0编辑  收藏  举报