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

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?

分析

题目很长,就是给你个二维数组,初始值都是0或1表示状态,状态会随着周围的8个数的和不同而变化,让你在原数组上进行状态改变,改变的时候要注意每个点都应该是同时改变的,如果先改变一个再改变下一个会导致信息改变。
改变规则:

现状态    邻居和    状态变化
1          <2        1->0
1         [2,3]      1->1
1          >3        1->0
0          =3        0->1

主要难点在原地上改变,又不能逐一判断改变。
这题使用状态记录法(自己起的名)。原来的状态可以是0,1,改成两位计数,第一位为下一个状态,第二位为现在的状态,就得到四个状态
00 01 10 11
得到现在状态的值 &1
得到下一个状态的值 >>1

因为默认下一个状态为0,所以只需要考虑下一个状态是1的情况

代码

public void gameOfLife(int[][] board) {
    int row = board.length;
    if(row == 0) return ;
    int col = board[0].length;

    for(int i = 0; i < row; ++i){
        for(int j = 0; j < col; ++j){
            int sum = getNeighborSum(board, row, col, i, j);

            if(board[i][j] == 1 && sum >= 2 && sum <= 3){
                board[i][j] = 3;
            }else if(board[i][j] == 0 && sum == 3){
                board[i][j] = 2;
            }
        }
    }

    for(int i = 0; i < row; ++i){
        for(int j = 0; j < col; ++j){
            board[i][j] = board[i][j] >> 1;
        }
    }
}

//有界则取临界值
public int getNeighborSum(int[][] board, int row, int col, int m, int n){
    int sum = 0;
    for(int x = Math.max(0, m -1); x <= Math.min(row-1, m+1); ++x){
        for(int y = Math.max(0, n-1); y <= Math.min(col-1, n+1); ++y){
            sum += board[x][y] & 1;
        }
    }
    return sum - board[m][n];
}

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