Topic:
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?
Ideas:
Here we assume that for a point, the meaning of the value is
0 : 上一轮是0,这一轮过后还是01 : 上一轮是1,这一轮过后还是12 : 上一轮是1,这一轮过后变为03 : 上一轮是0,这一轮过后变为1
Thus, for a node, if the point around it is 1 or 2, it means that the last round of the point is alive. Finally, after iterating through the array, we encode and then go back, that is, 0 and 2 are changed back to 0,1 and 3 to 1, on the line.
/** * @param {number[][]} board * @return {void} do not return anything, modify board In-place instead.*/varGameoflife =function(board) {varM=board.length,n=board[0].length; for(vari=0;i<m;i++){ for(varj=0;j<n;j++){ varLives=0; if(i>0) {lives+=board[i-1][j]==1| | board[i-1][j]==2?1:0; } if(i<m-1) {lives+=board[i+1][j]==1| | board[i+1][j]==2?1:0; } if(j>0) {lives+=board[i][j-1]==1| | board[i][j-1]==2?1:0; } if(j<n-1) {lives+=board[i][j+1]==1| | board[i][j+1]==2?1:0; } if(i>0&&j>0) {lives+=board[i-1][j-1]==1| | board[i-1][j-1]==2?1:0; } if(i>0&&j<n-1) {lives+=board[i-1][j+1]==1| | board[i-1][j+1]==2?1:0; } if(i<m-1&&j>0) {lives+=board[i+1][j-1]==1| | board[i+1][j-1]==2?1:0; } if(i<m-1&&j<n-1) {lives+=board[i+1][j+1]==1| | board[i+1][j+1]==2?1:0; } if(Board[i][j] = = 0 && lives = = 3) {Board[i][j]= 3; } Else if(Board[i][j] = = 1){ if(Lives < 2 | | lives > 3) Board[i][j]= 2; } } } for(vari = 0; I < m; i++){ for(varj = 0; J < N; J + +) {Board[i][j]= Board[i][j]% 2; } }};
"Array" Game of life