Advertisement
epsilon413

set matrix zero

Jun 26th, 2024
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | Source Code | 0 0
  1. class Solution {
  2. public:
  3.     void setZeroes(vector<vector<int>>& matrix) {
  4.         // Treat the first row and column as the flag row and flag column
  5.         // which keeps track of which column or row to mark with zeros
  6.         const int numRows = matrix.size();
  7.         const int numCols = matrix[0].size();
  8.  
  9.         // The overlapping cell of column 0
  10.         int col0 = 1;
  11.  
  12.         // Iterate over the matrix once, and mark the rows or columns
  13.         for(int i = 0; i < numRows; i++) {
  14.             for(int j = 0; j < numCols; j++) {
  15.                 // Not of our intereset
  16.                 if(matrix[i][j] != 0) continue;
  17.                 // Then, mark this row/column as marked
  18.  
  19.                 // This is the first col of the matrix, keeping track of rows
  20.                 matrix[i][0] = 0;
  21.                 // This is the first row of the matrix, keeping track of columns
  22.                 if(j != 0)
  23.                     matrix[0][j] = 0;
  24.                 else
  25.                     col0 = 0;
  26.             }
  27.         }
  28.  
  29.         // Iterate over once more and mark zeros
  30.         // Go from the other corner of the matrix
  31.         for(int i = numRows-1; i > 0; i--) {
  32.             for(int j = numCols-1; j > 0; j--) {
  33.                 // Either if the column flag is on, or row flag is on
  34.                 if(matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;
  35.             }
  36.         }
  37.  
  38.         // Check and mark the first column and row
  39.         if(matrix[0][0] == 0) {
  40.             for(int j = 0; j < numCols; j++) matrix[0][j] = 0;
  41.         }
  42.         if(col0 == 0) {
  43.             for(int i = 0; i < numRows; i++) matrix[i][0] = 0;
  44.         }
  45.     }
  46. };
Tags: leetcode
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement