# A relative long but well-comment understandable solution

• ``````class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int nRow = board.size(), nCol = board[0].size();
int dirX[] = {-1, -1, -1, 0, 0, 1, 1, 1};    // x coordinator change around 8 cells
int dirY[] = {-1, 0, 1, -1, 1, -1, 0, 1};    // y coordinator change around 8 cells
int count = 0;

// Refresh the board with transition state, transition state is a state between current and next state
for(int i = 0; i < nRow; i++) {
for(int j = 0; j < nCol; j++) {
count = 0;
// add value from 8 surrounding cells
for(int m = 0; m < 8; m++) {
// make sure the index is within the scope
if(((i + dirX[m]) >= 0)&&((i + dirX[m]) < nRow)&&((j + dirY[m]) >= 0)&&((j + dirY[m]) < nCol)) {
// here the cell value may be original value or transitin value
if((board[i + dirX[m]][j + dirY[m]] == 1)||(board[i + dirX[m]][j + dirY[m]] == 3)) count++;
}
}
// Get the transition state for each cell
board[i][j] = Count2Tran(board[i][j],count);
}
}

// Refresh the board to the next state value
for(int i = 0; i < nRow; i++) {
for(int j = 0; j < nCol; j++){
board[i][j] = State2Value(board[i][j]);
}
}
}

// Get the original value in the cell from the current transition state
int Tran2Ori(int state) {
int origin;
if(state == 0) origin = 0;        // state 0 means 0->0, then origin is 0
else if(state == 1) origin = 1;   // state 1 means 1->1, then origin is 1
else if(state == 2) origin = 0;   // state 2 means 0->1, then origin is 0
else if(state == 3) origin = 1;   // state 3 means 1->0, then origin is 1
return origin;
}

// Return the transition state from the origin cell state and the live cell count around it
int Count2Tran(int origin, int count) {
int state;
if((origin == 0)&&(count == 3)) state = 2;        // 2 means from 0->1
else if((origin == 0)&&(count != 3)) state = 0;   // 0 means remaining as 0, 0->0
else if((origin == 1)&&(count < 2)) state = 3;    // 3 means 1->0
else if((origin == 1)&&(count == 2)) state = 1;   // 1 mean remaining as 1, 1->1
else if((origin == 1)&&(count == 3)) state = 1;   // 1 mean remaining as 1, 1->1
else if((origin == 1)&&(count > 3)) state = 3;    // 3 means 1->0
return state;
}

// Get the value after transition
int State2Value(int state) {
int value;
if(state == 0) value = 0;   // state 0 means 0->0
if(state == 1) value = 1;   // state 1 means 1->1
if(state == 2) value = 1;   // state 2 means 0->1
if(state == 3) value = 0;   // state 3 means 1->0
return value;
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.