LeetCode 289. Game of Life

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

v2-d7cf7f811badb8998c363a584417a6a0_1440w.jpg

Description



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. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.


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


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?


描述



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


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


如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡;

如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活;

如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡;

如果死细胞周围正好有三个活细胞,则该位置死细胞复活;


根据当前状态,写一个函数来计算面板上细胞的下一个(一次更新后的)状态。下一个状态是通过将上述规则同时应用于当前状态下的每个细胞所形成的,其中细胞的出生和死亡是同时发生的。


示例:


输入: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
输出: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]


进阶:


你可以使用原地算法解决本题吗?请注意,面板上所有格子需要同时被更新:你不能先更新某些格子,然后使用它们的更新后的值再更新其他格子。


本题中,我们使用二维数组来表示面板。原则上,面板是无限的,但当活细胞侵占了面板边界时会造成问题。你将如何解决这些问题?


思路



  • 为了不使用额外的空间,体重只有两种值,即0和1.
  • 我们使用位运算,用二进制的最后以为存储题目给定的信息,用二进制的倒数第二位存储更新后的信息,最后我们再将所有的数向后移动一位即可.
  • 如果原位置为0,二进制的最后两位为00;如果其周围有3个1,那么这个位置下一次会复活变成1,于是当前位置的值变成10(二进制);否则下一次不会复活,依然是00
  • 如果当前位置是1,二进制最后两位为01,如果当前有2个活3个1,那么下一次继续存活,所以当前值为变为11(二进制),否则下一次会死亡,所以置为01(二进制).
  • 我们发现只有当前位置周围有3个1或者当前位置是1且周围有2个1是,当前的值才会变,并且为00-->10;01-->11,所以我们对当前的值&10即可.
  • 在更新完给定的board后,我们再将board所有的位置的值向右移动一位即可


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-02-08 10:26:20
# @Last Modified by:   何睿
# @Last Modified time: 2019-02-08 11:18:07
class Solution:
    def gameOfLife(self, board: 'List[List[int]]') -> 'None':
        """
        Do not return anything, modify board in-place instead.
        """
        row, col = len(board), len(board[0])
        for i in range(row):
            for j in range(col):
                count = self.__serach(board, i, j, row - 1, col - 1)
                # 如果当前位置是1,并且周围有两个1;或者当前周围有3个1
                if (board[i][j] and count == 2) or count == 3:
                    board[i][j] |= 0b10
        # 更新当前位置的信息
        for i in range(row):
            for j in range(col):
                board[i][j] >>= 1
        return
    def __serach(self, board, i, j, row, col):
        # 统计当前位置的临近的8个方格内1的个数
        count = 0
        # 获取行的边界
        row1, row2 = max(0, i - 1), min(row, i + 1)
        # 获取列的边界
        col1, col2 = max(0, j - 1), min(col, j + 1)
        for k in range(row1, row2 + 1):
            for m in range(col1, col2 + 1):
                count += (board[k][m] & 1)
        # 减去本身这个位置的值
        return count - (board[i][j] & 1)


源代码文件在这里.


目录
相关文章
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode 390. Elimination Game
给定一个从1 到 n 排序的整数列表。 首先,从左到右,从第一个数字开始,每隔一个数字进行删除,直到列表的末尾。 第二步,在剩下的数字中,从右到左,从倒数第一个数字开始,每隔一个数字进行删除,直到列表开头。 我们不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。 返回长度为 n 的列表中,最后剩下的数字。
73 0
LeetCode 390. Elimination Game
LeetCode 292. Nim Game
你和你的朋友,两个人一起玩 Nim游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
55 0
LeetCode 292. Nim Game
|
算法 索引
LeetCode 55. Jump Game
给定一个非负整数数组,您最初定位在数组的第一个索引处。 数组中的每个元素表示该位置的最大跳转长度。 确定您是否能够到达最后一个索引。
72 0
LeetCode 55. Jump Game
|
算法 索引
LeetCode 45. Jump Game II
给定一个非负整数数组,初始位置在索引为0的位置,数组中的每个元素表示该位置的能够跳转的最大部署。目标是以最小跳跃次数到达最后一个位置(索引)。
50 0
LeetCode 45. Jump Game II
|
决策智能
LeetCode之Nim Game
LeetCode之Nim Game
102 0