|
| 1 | + |
| 2 | +#include<bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +// Problem Statement: https://leetcode.com/problems/set-matrix-zeroes/ |
| 6 | + |
| 7 | +class Solution { |
| 8 | +public: |
| 9 | + void setZeroes(vector<vector<int>>& matrix){ |
| 10 | + |
| 11 | + bool firstRowZero = false; |
| 12 | + bool firstColumnZero = false; |
| 13 | + |
| 14 | + // Get status |
| 15 | + markZeros(matrix, firstRowZero, firstColumnZero); |
| 16 | + |
| 17 | + int row; |
| 18 | + int col; |
| 19 | + |
| 20 | + // change corrosponding cell values |
| 21 | + for(row = 1; row < matrix.size(); row++){ |
| 22 | + for(col = 1; col < matrix[0].size(); col++){ |
| 23 | + if(matrix[row][0] == 0 || matrix[0][col] == 0) |
| 24 | + matrix[row][col] = 0; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + // change 0th row and 0th col if valid |
| 29 | + if(firstRowZero){ |
| 30 | + for(col = 0; col < matrix[0].size(); col++) |
| 31 | + matrix[0][col] = 0; |
| 32 | + } |
| 33 | + if(firstColumnZero){ |
| 34 | + for(row = 0; row < matrix.size(); row++) |
| 35 | + matrix[row][0] = 0; |
| 36 | + } |
| 37 | <
10000
code class="diff-text syntax-highlighted-line addition">+ } |
| 38 | + |
| 39 | + |
| 40 | + void markZeros(vector<vector<int>>& matrix, bool& firstRowZero, bool& firstColumnZero){ |
| 41 | + |
| 42 | + int row; |
| 43 | + int col; |
| 44 | + |
| 45 | + // * get first row and col status before changing status for other cells |
| 46 | + if(matrix[0][0] == 0){ |
| 47 | + firstRowZero = firstColumnZero = true; |
| 48 | + } |
| 49 | + else{ |
| 50 | + for(row = 0; row < matrix[0].size(); row++){ |
| 51 | + if(matrix[0][row] == 0){ |
| 52 | + firstRowZero = true; |
| 53 | + break; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + for(col = 0; col < matrix.size(); col++){ |
| 58 | + if(matrix[col][0] == 0){ |
| 59 | + firstColumnZero = true; |
| 60 | + break; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + // status for other cells |
| 66 | + for(row = 1; row < matrix.size(); row++){ |
| 67 | + for(col = 1; col < matrix[0].size(); col++){ |
| 68 | + |
| 69 | + if(matrix[row][col] == 0){ |
| 70 | + matrix[row][0] = matrix[0][col] = 0; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | +}; |
| 77 | + |
0 commit comments