SHARE
TWEET

Untitled

a guest Oct 23rd, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. void setZeroes(vector<vector<int>>& matrix) {
  7.     int rows = matrix.size();
  8.     if (rows==0)
  9.         return;
  10.     int cols = matrix[0].size();
  11.  
  12.     //first handle headers
  13.     bool fillFirstCol = false;  //can't use [0][0] marker for both cols and rows
  14.     for (int r=0; r<rows; ++r) {
  15.         if (matrix[r][0]==0) fillFirstCol = true;
  16.     }
  17.     for (int c=1; c<cols; ++c) {
  18.         if (matrix[0][c]==0) matrix[0][0]=0;
  19.     }
  20.  
  21.     for (int r=1; r<rows; ++r) {
  22.         for (int c=1; c<cols; ++c) {
  23.             if (matrix[r][c]==0) {
  24.                 matrix[r][0] = 0;
  25.                 matrix[0][c] = 0;
  26.             }
  27.         }
  28.     }
  29.  
  30.     for (int r=1; r<rows; ++r) {
  31.         for (int c=1; c<cols; ++c) {
  32.             if (matrix[r][c]!=0 && (matrix[r][0]==0 || matrix[0][c]==0))
  33.                 matrix[r][c] = 0;
  34.         }
  35.     }
  36.  
  37.     //now fill headers (rows and columns).
  38.     for (int c=1; c<cols; ++c) {
  39.         if (matrix[0][0]==0) matrix[0][c]=0;
  40.     }
  41.     for (int r=0; r<rows; ++r) {
  42.         if (fillFirstCol) matrix[r][0]=0;
  43.     }
  44. }
  45.  
  46. void printv(const vector<vector<int>>& m) {
  47.     for (int r=0; r<m.size(); ++r) {
  48.         for (int c=0; c<m[0].size(); ++c)
  49.             cout << m[r][c] << " ";
  50.         cout << "\n";
  51.     }
  52. }
  53.  
  54. int main() {
  55.     vector<vector<int>> m {{1,1,1},{1,0,1},{1,1,1}}; //{{1,1,1},{0,1,2}}; //{{0,1}}; //{{0,1,2,0},{3,4,5,2},{1,3,1,5}};
  56.     setZeroes(m);
  57.     printv(m);
  58.     return 0;
  59. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top