Set Matrix Zeroes
Desicription
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int n = matrix.size(); int m = matrix[0].size(); vector<bool> row(n, 0); vector<bool> col(m, 0); for(int i = 0; i < n; ++i) for(int j = 0; j < m; ++j) if(!matrix[i][j]) row[i] = 1, col[j] = 1; for(int i = 0; i < n; ++i){ if(row[i]){ for(int j = 0; j < m; ++j) matrix[i][j] = 0; } } for(int j = 0; j < m; ++j){ if(col[j]){ for(int i = 0; i < n; ++i) matrix[i][j] = 0; } } } };
|