生命游戏

生命游戏

给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态:1 即为活细胞(live),或 0 即为死细胞(dead)。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律:
如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;
如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;
如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;
如果死细胞周围正好有三个活细胞,则该位置死细胞复活;
根据当前状态,写一个函数来计算面板上所有细胞的下一个(一次更新后的)状态。下一个状态是通过将上述规则同时应用于当前状态下的每个细胞所形成的,其中细胞的出生和死亡是同时发生的。

var gameOfLife = function(board) {
    if(board.length < 1) return;
    let n = board.length;
    let m = board[0].length;
    let copy = JSON.parse(JSON.stringify(board));
    
    // 用二进制表示细胞存活状态
    for(let i = 0; i < n; i++){
        for(let j = 0; j < m; j++){
            // 用来获取周围细胞存活数量
            let live = getCountLive(copy, i, j, n, m);
        
            if(board[i][j] === 1){
                // 活着情况
                if(live >= 2 && live <= 3){
                    board[i][j] = 3;
                }

            } else {
                // 死亡情况
                if(live === 3){
                    board[i][j] = 2;
                }
            }
        }
    }

    for(let i = 0; i < n; i++){
        for(let j = 0; j < m; j++){
            board[i][j] >>= 1;
        }
    }

};

const getCountLive = (board, i, j, x, y) => {
    // 用来计算周围八个坐标生存的值
    let diff = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, -1], [-1, 1], [1, -1]];
    let count = 0;
    for(let n = 0; n < diff.length; n++){
        let dx = i + diff[n][0];
        let dy = j + diff[n][1];
        if(dx < 0 || dx >= x || dy < 0 || dy >= y) continue;
        let current = board[dx][dy];
        count += current && 1;
    }
    return count;
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/game-of-life
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

posted @ 2020-04-02 11:21  wangziye  阅读(156)  评论(0编辑  收藏  举报