Question
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?
Solution
The key to this problem lies in the proper coding. We use two bits to represent the state of each cell.
After Prev
1 0 formerly dead, after an update for live
1 1 previously live, after an update to live
0 1 previously live, after an update for dead
0 0 formerly dead, after an update for dead
As a result we see that the prev bit can be operated with%, and the after bit can be used/manipulated.
So we iterate through the 2-dimensional array two times. The first time is to encode all the elements into the two-bit form above. The second time is the division operation, which gets after.
Time Complexity O (MN), Space cost O (1)
1 Public classSolution {2 Public voidGameoflife (int[] board) {3 int[] Directions = {{ -1,0},{1,0},{0,1},{0,-1},{-1,-1},{-1,1},{1,-1},{1,1}};4 intm = board.length, n = board[0].length;5 for(inti = 0; I < m; i++) {6 for(intj = 0; J < N; J + +) {7 intPrev =Board[i][j];8 intLivecount = 0, Deadcount = 0;9 for(intk = 0; K < 8; k++) {Ten intNewx = i + directions[k][0]; One intNewy = j + directions[k][1]; A if(Newx < 0 | | newx >= m | | Newy < 0 | | Newy >=N) { - Continue; - } the if(Board[newx][newy]% 2 = = 1) { -livecount++; - } - } + if(prev = = 0) { - if(Livecount = = 3) { +BOARD[I][J] + = 2; A } at}Else { - if(Livecount = = 2 | | livecount = = 3) { -BOARD[I][J] + = 2; - } - } - } in } - for(inti = 0; I < m; i++) { to for(intj = 0; J < N; J + +) { +BOARD[I][J] = Board[i][j]/2; - } the } * } $}
Game of Life Solutions