美文网首页
LeetCode-289-生命游戏

LeetCode-289-生命游戏

作者: 蒋斌文 | 来源:发表于2021-06-27 17:03 被阅读0次

    LeetCode-289-生命游戏

    289. 生命游戏

    难度中等348收藏分享切换为英文接收动态反馈

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

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

    1. 如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;
    2. 如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;
    3. 如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;
    4. 如果死细胞周围正好有三个活细胞,则该位置死细胞复活;

    下一个状态是通过将上述规则同时应用于当前状态下的每个细胞所形成的,其中细胞的出生和死亡是同时发生的。给你 m x n 网格面板 board 的当前状态,返回下一个状态。

    示例 1:

    img
    输入:board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
    输出:[[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
    

    示例 2:

    img
    输入:board = [[1,1],[1,0]]
    输出:[[1,1],[1,1]]
    

    提示:

    • m == board.length
    • n == board[i].length
    • 1 <= m, n <= 25
    • board[i][j]01

    进阶:

    • 你可以使用原地算法解决本题吗?请注意,面板上所有格子需要同时被更新:你不能先更新某些格子,然后使用它们的更新后的值再更新其他格子。
    • 本题中,我们使用二维数组来表示面板。原则上,面板是无限的,但当活细胞侵占了面板边界时会造成问题。你将如何解决这些问题?
    class Solution {
        public static void gameOfLife(int[][] board) {
            int N = board.length;
            int M = board[0].length;
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < M; j++) {
                    int neighbors = neighbors(board, i, j);
                    if (neighbors == 3 || (board[i][j] == 1 && neighbors == 2)) {
                        set(board, i, j);
                    }
                }
            }
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < M; j++) {
                    board[i][j] = get(board, i, j);
                }
            }
        }
    
        public static int neighbors(int[][] board, int i, int j) {
            int count = 0;
            count += ok(board, i - 1, j - 1) ? 1 : 0;
            count += ok(board, i - 1, j) ? 1 : 0;
            count += ok(board, i - 1, j + 1) ? 1 : 0;
            count += ok(board, i, j - 1) ? 1 : 0;
            count += ok(board, i, j + 1) ? 1 : 0;
            count += ok(board, i + 1, j - 1) ? 1 : 0;
            count += ok(board, i + 1, j) ? 1 : 0;
            count += ok(board, i + 1, j + 1) ? 1 : 0;
            return count;
        }
    
        public static boolean ok(int[][] board, int i, int j) {
            return i >= 0 && i < board.length && j >= 0 && j < board[0].length && (board[i][j] & 1) == 1;
        }
    
        public static void set(int[][] board, int i, int j) {
            board[i][j] |= 2;
        }
    
        public static int get(int[][] board, int i, int j) {
            return board[i][j] >> 1;
        }
    }
    
    image-20210627170240787

    相关文章

      网友评论

          本文标题:LeetCode-289-生命游戏

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