美文网首页
289. Game of Life

289. Game of Life

作者: FlynnLWang | 来源:发表于2016-12-28 23:16 被阅读0次

Question

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.


Code

public class Solution {
    private final int DD = 0;
    private final int LL = 1;
    private final int DL = 2;
    private final int LD = 3;
    
    public void gameOfLife(int[][] board) {
        if (board == null || board.length == 0) return;
        int m = board.length, n = board[0].length;
        
        int[] dx = {-1, 0, 1, -1, 1, -1, 0, 1};
        int[] dy = {1, 1, 1, 0, 0, -1, -1, -1};
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int live = 0, die = 0;
                for (int k = 0; k < 8; k++) {
                    int nx = i + dx[k];
                    int ny = j + dy[k];
                    
                    if (nx < 0 || nx >= m || ny < 0 || ny >= n) {
                        die++;
                        continue;
                    }
                    
                    if (board[nx][ny] == 0 || board[nx][ny] == 2) die++;
                    else live++;
                }
                if (board[i][j] == 1) {
                    if (live < 2) {
                        board[i][j] = 3;
                    } else if (live > 3) {
                        board[i][j] = 3;
                    }
                } else {
                    if (live == 3) {
                        board[i][j] = 2;
                    }
                }
            }
        }
        
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 2) board[i][j] = 1;
                if (board[i][j] == 3) board[i][j] = 0;
            }
        }
    }
}

Solution

用4个int分别代表状态转换的情况:0表示由死到死,1表示由生到生,2表示由死到生,3表示由生到死。遍历neighbor的时候,需查看neighbor状态转换前的状态。

相关文章

网友评论

      本文标题:289. Game of Life

      本文链接:https://www.haomeiwen.com/subject/omduvttx.html