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

Example 1:

Input: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

Example 2:

Input: 
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
Output: 
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]




思路:
用矩阵的第一行存储,哪一列需要置0
用矩阵的第一列存储,哪一行需要置0
 1 class Solution {
 2 public:
 3     void setZeroes(vector<vector<int>>& matrix) {
 4         int rows = matrix.size();
 5         int cols = matrix[0].size();
 6         int col0=1,row0=1;
 7 
 8         
 9         for(int i = 0;i<rows;i++)
10             if(matrix[i][0]==0)col0=0;
11         
12         for(int j = 0;j<cols;j++)
13             if(matrix[0][j]==0)row0=0;
14         
15         
16         
17         for(int i = 1;i<rows;i++)
18             for(int j = 1;j<cols;j++)
19                 if(matrix[i][j]==0){
20                     matrix[0][j] = 0;
21                     matrix[i][0] = 0;
22                 }
23     
24         
25         
26         for(int i = 1;i<rows;i++)
27               for(int j = 1;j<cols;j++)
28                 if(matrix[i][0]==0||matrix[0][j]==0)
29                     matrix[i][j]=0;
30         
31         if(col0==0){
32             for(int i = 0;i<rows;i++)
33                 matrix[i][0] = 0;
34         }
35         if(row0==0){
36         for(int j = 0;j<cols;j++)
37             matrix[0][j]= 0 ;
38         }
39         
40     }
41 };

 

posted @ 2019-01-08 17:13  乐乐章  阅读(118)  评论(0编辑  收藏  举报