According to the Wikipedia's article: "The Game of Life, also known simply as Life, was a cellular automaton devised by the British mathematician John Horton Conway in 1970. "
Given a board with m - n cells, each cell have an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from t He above Wikipedia article):
- Any live cell with fewer than-live neighbors dies, as if caused by under-population.
- Any live cell with a or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population.
- Any dead cells with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given it current state.
Follow up:
- Could You solve it in-place? Remember the board needs to be updated at the same time:you cannot update some cells first and then use their update D values to update the other cells.
- In this question, we represent the board using a 2D array. In principle, the board was infinite, which would cause problems when the active area encroaches the border of the array. How would address these problems?
Analyse:you could use aid vectors to record the transferred state, or set different values while transfer without the aid Vector.
classSolution { Public: //get the transfer state of board after one updatevector<vector<int> > Transferstate (vector<vector<int> > &Board) {Vector<vector<int> > Tempresult (Board.size (), vector<int> (board[0].size (),-1)); //Compute the number of neighbours ' 1 for(inti =0; I < board.size (); i++) { for(intj =0; J < Board[i].size (); J + +) { intNeighbor =0; for(intm = i-1; M <= i +1; m++) { if(M <0|| M >= board.size ())Continue; for(intn = J-1; N <= J +1; n++) { if(N <0|| n >= board[i].size () | | (m = = I && n = = j))Continue; if(Board[m][n] = =1) neighbor++; } } if(Board[i][j] = =1) Tempresult[i][j]= (Neighbor = =2|| Neighbor = =3) ?1:0; ElseTempresult[i][j]= Neighbor = =3?1:0; } } returnTempresult; } //Compute the result after the transfer voidComputeresult (vector<vector<int> > Tempresult, vector<vector<int> >&Board) { for(inti =0; I < board.size (); i++) for(intj =0; J < Board[i].size (); J + +) Board[i][j]=Tempresult[i][j]; } voidGameoflife (vector<vector<int>>&Board) { if(Board.empty () | | board[0].empty ())return; Vector<vector<int> > Tempresult =transferstate (board); Computeresult (tempresult, board); }};
Game of Life