原题链接在这里:https://leetcode.com/problems/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. 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:

  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?

题解:

简单的想法就是copy 原来矩阵,然后根据copy 来修改原来的矩阵,如此做会使用O(m*n) space.

如何做到In-space呢,我们需要根据改动前的状态来数出live cell 的个数,已经更改的点如何知道原有的状态呢。就要多mark出几种conditions.

Dead->Dead: Condition 0;

Live->Live : Condition 1;

Live->Dead: Condition 2;

Dead->Live:Condition 3

如此在数数的时候如果该位置是1 或 2, 这个位置原有的状态都是live. 就都要算.

最后通过把所有的数%2来得到更改后的状态。

如何定义这四种状态?第一个原因是通过如此顺序是因为0本身就是dead cell, 1本身就是live cell, 如此在countLive完成后可以尽量少改动数组,如果还是live的1的状态就不用动了.

第二个原因最后对0,1,2,3改回0,1时 可以直接通过%2改动省事。

如果需要记住原有状态就可以通过增加condition 来搞定.

Time Complexity: O(m*n). Space: O(1).

AC Java:

 public class Solution {
public void gameOfLife(int[][] board) {
if(board == null || board.length == 0 || board[0].length == 0){
return;
}
int m = board.length;
int n = board[0].length;
//Mark four conditions
// Dead->Dead: 0; Live->Live : 1; Live->Dead: 2; Dead->Live:3
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
int count = getLive(board, i, j); //计算周围8个位置上原来有多少个live cell
if(board[i][j] == 0 && count == 3){ //dead -> live
board[i][j] = 3;
}else if(board[i][j] == 1 && (count < 2 || count > 3)){ //live -> dead
board[i][j] = 2;
}
}
}
//Seconde iteration, mark 2 to 0, mark 3 to 1.
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
board[i][j] = board[i][j]%2;
}
}
}
//计算周围8个位置上有多少个原来是live 的 细胞
private int getLive(int [][] board, int i, int j){
int count = 0;
for(int x = i-1; x<=i+1; x++){
for(int y = j-1; y<=j+1; y++){
if(x<0 || x>=board.length || y<0 || y>=board[0].length || (x == i && y == j)){
continue;
}
if(board[x][y] == 1 || board[x][y] == 2){
count++;
}
}
}
return count;
}
}

类似Set Matrix Zeroes.

LeetCode Game of Life的更多相关文章

  1. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  2. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  3. [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  4. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  5. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  6. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  7. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  8. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  9. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  10. Leetcode 笔记 101 - Symmetric Tree

    题目链接:Symmetric Tree | LeetCode OJ Given a binary tree, check whether it is a mirror of itself (ie, s ...

随机推荐

  1. C#时间格式化(Datetime)用法详解

    Datetime.ToString(String, IFormatProvider) 参数format格式详细用法: 格式字符 关联属性/说明 d ShortDatePattern D LongDat ...

  2. (译)V8引擎介绍

    V8是什么? V8是谷歌在德国研发中心开发的一个JavaScript引擎.开源并且用C++实现.可以用于运行于客户端和服务端的Javascript程序. V8设计的初衷是为了提高浏览器上JavaScr ...

  3. 三层架构实例 VB.NET版

    三层实例 首先发现感慨,对于三成这块,用到都是一些面向对象的特征,尤其是对象的实例化.如果你不是很注意的话,那么,你就会一头雾水,就像我一样,慢慢的雾里看花,最后也是走出来的,不过用的事件是相当的. ...

  4. Apache Storm技术实战之1 -- WordCountTopology

    欢迎转载,转载请注意出处,徽沪一郎. “源码走读系列”从代码层面分析了storm的具体实现,接下来通过具体的实例来说明storm的使用.因为目前storm已经正式迁移到Apache,文章系列也由twi ...

  5. DWZ框架一些技巧

    DWZ框架from表单提交后关闭对话框 注意大小写 <input type="hidden" name="callbackType" value=&quo ...

  6. PHP 计算出内存最高占用.

    PHP 计算出内存最高占用.   代码可以计算出内存是否完全被使用, ini设置处:memory_limit = 1024M  代码跑完将显示如下信息: memory_limit:320M  all ...

  7. web.xml总结整理

    web.xml 配置的详细解读 web.xml (部署描述符文件) 整理参考:      加载顺序 ServletContext-->listener->filter->srvlet ...

  8. mysql 存储过程 php版本

    <?php /** * PHP操作Mysql存储过程示例 * * @author flyer0126 * @date 2011-12-23 * */ //配置数据库连接信息 $hostname ...

  9. ROSE User Case View

    用例视图(User Case View) 在面向对象的分析过程中,此视图应该是需求分析的过程中采用,主要包括如下过程 01涉众分析--->02业务分析--->03概念分析--->04 ...

  10. [dpdk] 读开发指南(1)

    该文档是随着对于文档的阅读进度,不断增加的阅读笔记.主要内容以大纲为主,以及记录帮助记忆的内容. 在之后的实际应用中,也不随着不断的深入理解,逐渐丰富各大纲下面的内容. 1. 前期准备:设置两个环境变 ...