knakul853

Untitled

Jun 12th, 2020
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. /**
  2. knakul853
  3. **/
  4. class Solution {
  5. public:
  6.     void gameOfLife(vector<vector<int>>& board) {
  7.        
  8.         if(board.empty()) return ;
  9.        
  10.         int n = (int)board.size();
  11.         int m = (int)board[0].size();
  12.        
  13.         for(int i=0; i<n; i++)   // [2nd bit 1st bit] <- after preocess remove the first bit( >>=1 );
  14.         {
  15.             for(int j=0; j<m; j++)
  16.             {
  17.                 int lives = Lives(board, i, j);
  18.                 if(board[i][j] == 1 && lives >=2 && lives <= 3)
  19.                 {
  20.                     board[i][j] = 3;   //  it will not change the current state.eg 01->11 only next state changed
  21.                 }
  22.                
  23.                 else if( board[i][j] == 0 && lives == 3)
  24.                 {
  25.                     board[i][j] = 2;
  26.                 }
  27.             }
  28.         }
  29.        
  30.         for( int i = 0; i < n; i++)
  31.         {
  32.             for(int j = 0; j < m; j++ )
  33.             {
  34.                 board[i][j] >>=1;
  35.             }
  36.         }
  37.        
  38.     }
  39.    
  40.     private :
  41.     int Lives(vector<vector<int>>&board, int i, int j )
  42.     {
  43.         int n = (int)board.size();
  44.         int m = (int)board[0].size();
  45.        
  46.         int lives = 0;
  47.         for(int k=max(0, i-1); k<=min(n-1, i+1); k++ )
  48.         {
  49.             for(int l=max(0, j-1); l<=min(m-1, j+1); l++ )
  50.             {
  51.                 lives+=board[k][l]&1;
  52.             }
  53.         }
  54.        
  55.         lives -= board[i][j]&1;
  56.        
  57.         return lives;
  58.     }
  59. };
Add Comment
Please, Sign In to add comment