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组成,0代表死亡的元素,1代表活的元素。数组是变化的,变化的规则有四个,当一个活的元素周围有两个或三个活的元素时,下一个阶段它会存活;如果它的周围活的元素小于两个或者多于三个下一个阶段它都将死亡。对于一个死亡的元素,如果它的周围有三个活的元素,下一个阶段它就会复活。

我们一次判断数组中的元素,得到它周围有几个活的元素,根据规则判断它下一个阶段是否存活,如果存活就进行标记,一次处理完所有的元素。最后将标记的元素变为1,其余为0即可。代码如下:
public class Solution {
    public void gameOfLife(int[][] board) {
        if(board == null || board.length == 0) return;
        int m = board.length;
        int n = board[0].length;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                int countLive = getLive(i, j, m, n, board);
                if(board[i][j] == 1) {
                    if(countLive == 2 || countLive == 3)
                        board[i][j] += 10;
                } else {
                    if(countLive == 3)
                        board[i][j] += 10;
                }
            }
        }
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(board[i][j] / 10 == 1) {
                    board[i][j] = 1;
                } else {
                    board[i][j] = 0;
                }
            }
        }
    }
    private int getLive(int x, int y, int m, int n, int[][] board) {
        int count = 0;
        for(int i = x - 1; i <= x + 1; i ++) {
            for(int j = y - 1; j <= y + 1; j ++) {
                if(i < 0 || j < 0 || i == m || j == n || (i == x && j == y)) continue;
                if(board[i][j] % 10 == 1) count ++;
            }
        }
        return count;
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2279213