According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has 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 the above Wikipedia article):
- Any live cell with fewer than two live neighbors dies, as if caused by under-population.
- Any live cell with two 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 cell 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 its current state.
Follow up:
- Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
- In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?
本题题目比较长,其实就是如下的表格:
neighbor | current state | next state |
1 | 1 | 0 |
2,3 | 1 | 1 |
>4 | 1 | 0 |
3 | 0 | 1 |
这种题目和single number,single number2 比较相似,用的都是用位来存储状态。本题用第一位表示next state,第二位表示current state
代码如下:
1 //1->0 neighbor 1 2 //1->1 neighbor 2,3 3 //1->0 neightbor >4 4 //0->1 neightbor 3 5 public class Solution { 6 public void gameOfLife(int[][] board) { 7 if(board.length==0) return; 8 for(int i=0;i<board.length;i++){ 9 for(int j=0;j<board[0].length;j++){ 10 int live = liveneighbor(board,i,j); 11 if(board[i][j]==1&&live>=2&&live<=3){ 12 board[i][j]=(board[i][j]<<1)+1; 13 }else if(board[i][j]==0&&live==3){ 14 board[i][j] = 1<<1; 15 } 16 } 17 } 18 for(int i=0;i<board.length;i++){ 19 for(int j=0;j<board[0].length;j++){ 20 board[i][j] = board[i][j]>>1; 21 } 22 } 23 } 24 public int liveneighbor(int[][] board,int row,int col){ 25 int m = board.length; 26 int n =board[0].length; 27 int live = 0; 28 for(int x = Math.max(0,row-1);x<=Math.min(m-1,row+1);x++){ 29 for(int y=Math.max(0,col-1);y<=Math.min(n-1,col+1);y++){ 30 live+=board[x][y]&1; 31 } 32 } 33 live-=board[row][col]; 34 return live; 35 } 36 }