Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- knakul853
- **/
- class Solution {
- public:
- void gameOfLife(vector<vector<int>>& board) {
- if(board.empty()) return ;
- int n = (int)board.size();
- int m = (int)board[0].size();
- for(int i=0; i<n; i++) // [2nd bit 1st bit] <- after preocess remove the first bit( >>=1 );
- {
- for(int j=0; j<m; j++)
- {
- int lives = Lives(board, i, j);
- if(board[i][j] == 1 && lives >=2 && lives <= 3)
- {
- board[i][j] = 3; // it will not change the current state.eg 01->11 only next state changed
- }
- else if( board[i][j] == 0 && lives == 3)
- {
- board[i][j] = 2;
- }
- }
- }
- for( int i = 0; i < n; i++)
- {
- for(int j = 0; j < m; j++ )
- {
- board[i][j] >>=1;
- }
- }
- }
- private :
- int Lives(vector<vector<int>>&board, int i, int j )
- {
- int n = (int)board.size();
- int m = (int)board[0].size();
- int lives = 0;
- for(int k=max(0, i-1); k<=min(n-1, i+1); k++ )
- {
- for(int l=max(0, j-1); l<=min(m-1, j+1); l++ )
- {
- lives+=board[k][l]&1;
- }
- }
- lives -= board[i][j]&1;
- return lives;
- }
- };
Add Comment
Please, Sign In to add comment