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?

思路

直接的思路是用o(m+n)的空间来记录m行和n列是否存在0, 但是需要用固定空间的解决方法,可以考虑使用原先数据提供的空间,进而想到用原数组的第一行和第一列来记录。另外由于还需要第一行和第一列是否需要置为0,所以使用两个bool变量来存储原先第一行和第一列是否存在0即可。

代码

 1     void setZeroes(vector<vector<int> > &matrix) {
 2         // Note: The Solution object is instantiated only once and is reused by each test case.
 3         bool hasZeroRow = false, hasZeroColumn = false;
 4         int i,j;
 5         int m = matrix.size();
 6         if(m == 0)
 7             return;
 8         int n = matrix[0].size();
 9         if(n == 0)
10             return;
11         for(i = 0; i < n; i++){
12             if(matrix[0][i] == 0){
13                 hasZeroRow = true;
14                 break;
15             }
16         }
17         for(i = 0; i < m; i++){
18             if(matrix[i][0] == 0){
19                 hasZeroColumn = true;
20                 break;
21             }
22         }
23         for(i = 1; i < m; i++){
24             for(j = 1; j < n; j++){
25                 if(matrix[i][j] == 0){
26                     matrix[0][j] = 0;
27                     matrix[i][0] = 0;
28                 }
29             }
30         }
31         for(i = 1; i < n; i++){
32             if(matrix[0][i] == 0){
33                 for(j = 0; j < m; j++){
34                     matrix[j][i] = 0;
35                 }
36             }
37         }
38         for(i = 1; i < m; i++){
39             if(matrix[i][0] == 0){
40                 for(j = 0; j < n; j++){
41                     matrix[i][j] = 0;
42                 }
43             }
44         }
45         if(hasZeroRow){
46             for(i = 0; i < n; i++)
47                 matrix[0][i] = 0;
48         }
49         if(hasZeroColumn){
50             for(i = 0; i < m; i++)
51                 matrix[i][0] = 0;
52         }
53     }
原文地址:https://www.cnblogs.com/waruzhi/p/3388423.html