1: class Solution {
2: public:
3: void setZeroes(vector<vector<int>>& matrix) {
4: int rows = matrix.size();
5: int cols = matrix[0].size();
6: bool col0 = true, row0 = true;
7: for (int i = 0; i < rows; i++) {
8: if (matrix[i][0] == 0) {
9: col0 = false;
10: break;
11: }
12: }
13: for (int j = 0; j < cols; j++) {
14: if (matrix[0][j] == 0) {
15: row0 = false;
16: break;
17: }
18: }
19: for (int i = 0; i < rows; i++) {
20: for (int j = 0; j < cols; j++) {
21: if (matrix[i][j] == 0) {
22: matrix[i][0] = 0;
23: matrix[0][j] = 0;
24: }
25: }
26: }
27: for (int i = 1; i < rows; i++) {
28: if (matrix[i][0] == 0) {
29: for (int j = 1; j < cols; j++) {
30: matrix[i][j] = 0;
31: }
32: }
33: }
34: for (int j = 1; j < cols; j++) {
35: if (matrix[0][j] == 0) {
36: for (int i = 1; i < rows; i++) {
37: matrix[i][j] = 0;
38: }
39: }
40: }
41: if (!col0) {
42: for (int i = 0; i < rows; i++) {
43: matrix[i][0] = 0;
44: }
45: }
46: if (!row0) {
47: for (int j = 0; j < cols; j++) {
48: matrix[0][j] = 0;
49: }
50: }
51: }
52: };
Saturday, June 25, 2016
73. Set Matrix Zeroes
To solve it in place, I'll use the first row and first column to record the 0s.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment