leetcode Game of Life

leetcode Game of Life

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):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. 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.

Follow up:

  1. 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.
  2. 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?

题目地址:leetcode Game of Life

题意:

给定一个m*n的矩阵,根据生命游戏的规则求下一个时刻这个矩阵的状态

生命游戏的规则如下(邻居均为八个方向):

  1. 活的细胞的邻居少于2个是活的,这个细胞会孤独致死
  2. 活的细胞的邻居有2~3个是活的,这个细胞下一刻还是活的
  3. 活的细胞邻居超过3个是活的,这个细胞会死亡
  4. 死的细胞人邻居有3个是活的,这个细胞下一刻也会复活

 

思路:

说白了仅有当活的细胞邻居2~3个是活的,这个细胞下一次才是活的,死的细胞邻居3个活的,下一刻这个细胞也是活的

所以写出如下代码:

 

Follow up:

如果不开一个辅助的数组呢?

我们假设有4个状态,比如2表示一开始为1,但是之后应该为0的状态,3表示一开始为0,但是之后为1 的状态,总结状态如下:

0 : 0 -> 0

1 : 1 -> 1

2 : 1 -> 0

3 : 0 -> 1

于是,我们计算邻居活细胞的个数,应该把状态2也计算进去。

根据状态做相应的修改,最后对2取模即可。

 

 

 

 

本博客若无特殊说明则由 hrwhisper 原创发布
转载请点名出处:细语呢喃 > leetcode Game of Life
本文地址:https://www.hrwhisper.me/leetcode-game-of-life/

听说长得好看的已经打赏了

Leetcode . permalink.

One thought on “leetcode Game of Life

Leave a Reply

Your email address will not be published. Required fields are marked *