life game
class Solution {
public:
//checking if we are inside the board or not
bool issafe(int i, int j, int m, int n)
{
if(i < 0 || j< 0 || j>= n || i >= m )
return false;
return true;
}
//helper function
void change(int i, int j, int m, int n, vector<vector<int>> &board, vector<vector<int>> &newboard)
{
int count0 = 0, count1 = 0;
//array for checking all 8 positions
int xpos[8] = {-1, 1, 0, 0, -1, -1, 1, 1};
int ypos[8] = {0, 0, -1, 1, -1, 1, -1, 1};
// Evaluating number of 0's and 1's
for(int k = 0; k<8; k++)
{
if(issafe(i+xpos[k] , j+ypos[k] , m, n))
count1+= board[i+xpos[k]][j+ypos[k]];
}
count0 = 8-count1;
//Applying conditions and updating the board
if(count1 < 2 && board[i][j] == 1)
newboard[i][j] = 0;
else if((count1 == 2 || count1 == 3) && board[i][j] == 1 )
newboard[i][j] = 1;
else if(count1 > 3 && board[i][j] == 1)
newboard[i][j] = 0;
else if(count1 == 3 && board[i][j] == 0)
newboard[i][j] = 1;
}
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
int n = board[0].size();
vector<vector<int>> newboard = board;
//traversing the original board
for(int i = 0; i<m; i++)
for(int j = 0; j<n; j++)
change(i, j, m, n, board, newboard);
//assigning the values of the newboard to the original board
board = newboard;
}
};