Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

289. Game of Life #92

Open
Tcdian opened this issue Apr 2, 2020 · 1 comment
Open

289. Game of Life #92

Tcdian opened this issue Apr 2, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 2, 2020

289. Game of Life

根据 百度百科 ,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机。

给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态:1 即为活细胞(live),或 0 即为死细胞(dead)。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律:

如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;
如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;
如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;
如果死细胞周围正好有三个活细胞,则该位置死细胞复活;
根据当前状态,写一个函数来计算面板上所有细胞的下一个(一次更新后的)状态。下一个状态是通过将上述规则同时应用于当前状态下的每个细胞所形成的,其中细胞的出生和死亡是同时发生的。

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]
]

Note

  • 你可以使用原地算法解决本题吗?请注意,面板上所有格子需要同时被更新:你不能先更新某些格子,然后使用它们的更新后的值再更新其他格子。
  • 本题中,我们使用二维数组来表示面板。原则上,面板是无限的,但当活细胞侵占了面板边界时会造成问题。你将如何解决这些问题?
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 2, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
var gameOfLife = function(board) {
    const DEATH = 2;
    const RELIVE = 3;
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[0].length; j++) {
            const liveCount = calcLive(board, i, j);
            if (board[i][j] === 1) {
                if (liveCount < 2 || liveCount > 3) {
                    board[i][j] = DEATH;
                }
            }
            if (board[i][j] === 0) {
                if (liveCount === 3) {
                    board[i][j] = RELIVE;
                }
            }
        }
    }

    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            board[i][j] %= 2;
        }
    }

    function calcLive(board, i, j) {
        let count = 0;
        const direction = [-1, -1, -1, 0, 1, 1, 1, 0, -1, -1];
        for (let d = 0; d < 8; d++) {
            const x = i + direction[d];
            const y = j + direction[d + 2];
            if (x >= 0 && x < board.length && y >= 0 && y < board[0].length) {
                if (board[x][y] === 1 || board[x][y] === DEATH) {
                    count += 1;
                }
            }
        }
        return count;
    }
};

@Tcdian Tcdian added the LeetCode label Apr 2, 2020
@Tcdian Tcdian removed the LeetCode label Apr 23, 2020
@Tcdian Tcdian added the Array label May 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant