289. Game of Life

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):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. 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. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
Output: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]

Follow up:

  1. 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.
  2. 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?

属于一道技巧性比较强的题。

首先,如果使用额外的m*n空间的话,就没什么好做的了。这里要求的是不使用额外空间。

解法如下:

首先,我们将1(live)或者0(dead)这样理解:

1就是 01 代表next state = 0, current_state = 1

0就是 00 代表next state = 0, current_state = 0

那么也就是说,board[i][j]同时记录着current state和next state。而且next state默认为0(dead)

那么为了满足4条规则,我们需要处理以下两种情况:

(1) current state = 1且live neighbors个数为2或者3

          这种情况下,next state 为 1(live)。因此board[i][j]要由 01 变为 11, 即从1变为3

(1) current state = 0且live neighbors个数为3

          这种情况下,next state 为 1(live)。因此board[i][j]要由 00 变为 10, 即从0变为2

那么在改变next state的时候,并没有改变current state的过程。因此就不再需要额外的空间了

代码如下:

class Solution {
    public void gameOfLife(int[][] board) {
        //borad[i][j] = 0代表 00 即next:dead  present:dead
        //borad[i][j] = 1代表 01 即next:dead  present:live
        int m = board.length;
        int n = board[0].length;
        for(int i = 0;i>1;
                board[i][j] = next_state;
            }
        }
    }
    
    private int get_live_neigh(int[][] board,int i,int j){
        int res = 0;
        for(int m = -1;m<=1;m++){
            for(int n  = -1;n<=1;n++){
                if(!(m==0&&n==0) && i+m>=0 && i+m=0 && j+n

 

你可能感兴趣的:(289. Game of Life)