# C++ in-place solution, use small trick

• my code looks like this:

``````class Solution {
public:
void gameOfLife(vector< vector<int> >& board) {
int rows = board.size();
if(rows < 1)
return;
int columns = board[0].size();
if( columns < 1)
return;
for (int i = 0; i < rows; ++i) {
for (int j=0; j < columns; ++j) {
// use 4 status to identify one cell
// current status is 0, next status should be 0, gives it with value 6
// current status is 0, next status should be 1, gives it with value 2
// current status is 1, next status should be 0, gives it with value 3
// current status is 1, next status should be 1, gives it with value 5
int neightbors = this->getNeightborCount(board, i, j);
if(neightbors < 2 || neightbors > 3)
{
board[i][j] = -3*board[i][j] + 6;
}
else if(neightbors == 2)
{
board[i][j] = -board[i][j] + 6;
}
else{
board[i][j] = 3*board[i][j] + 2;
}

}// for columns
}// for rows

// use 0 or 1 to reassign the cell status
for (int i = 0; i < rows; ++i) {
for (int j=0; j < columns; ++j) {
if(board[i][j]%3 == 0)
board[i][j] = 0;
else
board[i][j] = 1;
}// for columns
}// for rows

}

int getNeightborCount(vector< vector<int> >& board, int row_id, int col_id)
{
int rows = board.size();
if(rows == 0)
return 0;
int columns = board[0].size();
if (columns <= 0) {
return 0;
}
int sum = 0;
int cur_row = row_id - 1, cur_col = 0;
while(cur_row <= row_id + 1)
{
if(cur_row < 0 || cur_row > rows-1){
++cur_row;
continue;
}
cur_col = col_id - 1;
while( cur_col <= col_id + 1)
{
if(cur_col < 0 || cur_col > columns - 1){
++cur_col;
continue;
}
sum += (board[cur_row][cur_col]%2);
++cur_col;
}
++cur_row;
}
return sum - (board[row_id][col_id]%2);
}

void printBoard(vector< vector< int > >& board)
{
int rows = board.size();
if(rows == 0)
return;
int columns = board[0].size();
if(columns <= 0)
return;
for (int i=0; i < rows; ++i) {
for (int j=0; j<columns; ++j) {
cout<<board[i][j]<<"\t";
}
cout<<endl;
}
cout<<endl;
}
};
``````

ok , the printBoard method is just for debuging. Comments are welcome.

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