题目

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.

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?

分析

基于一个生命游戏的题目,游戏介绍

生死判断条件:

  1. 一個活的格子若只有一個或沒有鄰居, 在下一秒將因寂寞而亡;
  2. 一個活的格子若有四個或四個以上的鄰居, 在下一秒將因拥擠而亡;
  3. 一個活的格子若有二個或三個鄰居, 在下一秒將継續活著;
  4. 一個死的格子若有三個鄰居, 在下一秒將活過來;

题目要求inplace实现,不允许额外申请空间。

若是不考虑占用空间,我们很容易可以解决该问题。首先,保存原始棋盘用于计算邻居live状态的数目。然后依据条件修改board每个cell的状态即可。

若是不允许申请空间,我们必须在不改变原始棋盘状态的情况下,记录出每个cell应该怎么变化;

使用不同数值(十进制)代表状态 0 :dead; 10 :dead—>live; 11:live—>live; 1:live;

具体实现见代码!

AC代码

class Solution {
public:
//方法一:复制原来棋盘,空间复杂度为O(n)
void gameOfLife1(vector<vector<int>>& board) {
if (board.empty())
return; //求出所给定棋盘的行列
int m = board.size(), n = board[0].size(); vector<vector<int>> tmp(board.begin(), board.end());
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
int count = getLiveNum(tmp, i, j);
if (board[i][j] == 0)
{
//dead状态
if (count == 3)
board[i][j] = 1; //dead —> live
}//if
else{
//live状态
if (count > 3)
{
board[i][j] = 0; //live—>dead
}//if
//若是count == 2 || count == 3 则live—>dead,board[i][j]值不变
}//else
}//for
}//for
return;
} //方法二:inplace 使用不同数值(十进制)代表状态 0 :dead; 10 :dead—>live; 11:live—>live; 1:live;
void gameOfLife(vector<vector<int>>& board) {
if (board.empty())
return; //求出所给定棋盘的行列
int m = board.size(), n = board[0].size();
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
int count = getLiveNum(board, i, j);
if (board[i][j] == 0)
{
//dead状态
if (count == 3)
board[i][j] += 10; //dead —> live
}
else{
//live状态
if (count == 2 || count == 3)
{
board[i][j] += 10; //live—>live
}//if
//若是count>=4 则live—>dead,board[i][j]值不变
}//else
}//for
}//for
//更新状态
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
board[i][j] /= 10;
}//for
}//for
return;
} //计算位于(r,c)邻居,live状态的数量
int getLiveNum(vector<vector<int>> &board, int x, int y)
{
int count = 0;
for (int i = x - 1; i <= x + 1; ++i)
{
for (int j = y - 1; j <= y + 1; ++j)
{
if (i < 0 || j < 0 || i >= board.size() || j >= board[x].size() || (x == i && j == y))
{
continue;
}
else{
if (board[i][j] % 10 == 1)
++count;
}//else
}//for
}//for
return count;
} };

GitHub测试程序源码

LeetCode(289)Game of Life的更多相关文章

  1. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  2. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  3. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  4. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  5. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  6. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

  7. LeetCode(107) Binary Tree Level Order Traversal II

    题目 Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from l ...

  8. LeetCode(4)Median of Two Sorted Arrays

    题目 There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the ...

  9. Leetcode(1)两数之和

    Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...

随机推荐

  1. Core2.0 项目到2.1

    Core2.0 项目到2.1 https://www.cnblogs.com/FlyLolo/p/ASPNETCore2_10.html .NET Core 2.1 终于发布了, 赶紧升级一下. 一. ...

  2. 解决win10下python3和python2共存pip的问题

    经过在查阅网友的各种经验,发现仍然解决不了问题,python2和python3在win10下的安装就不再演示了,直接在python的官网下载就好,我机器上使用的是python2.7.15和python ...

  3. 教你如何在 IDEA 远程 Debug ElasticSearch

    前提 之前在源码阅读环境搭建文章中写过我遇到的一个问题迟迟没有解决,也一直困扰着我.问题如下,在启动的时候解决掉其他异常和报错后,最后剩下这个错误一直解决不了: [2018-08-01T09:44:2 ...

  4. 关于Memcache的连接

    addServer 在说Memcache的长连接(pconnect)和短连接(connect)之前要先说说Memcache的addServer,Memcache的addServer是增加一个服务器到连 ...

  5. asp.net MVC 4.0 View回顾——布局页与分部页

    asp.net MVC 4.0中总结 视图里加载部分视图几种方法 @RenderPage() 但它不能使用 原来视图的 Model 和 ViewData ,只能通过参数来传递. @RenderPage ...

  6. VS2012,更新补丁后的残忍--创建项目未找到与约束匹配的导出

    解决方法网址:http://blog.csdn.net/jly4758/article/details/18660945

  7. linux 安装jdk (二进制文件安装)

    1.下载jdk 此处以1.7 为例 :jdk-7u79-linux-x64.tar.gz 2.通过ssh将安装介质传到服务器 我一般放在 /opt 目录下 3.用tar 命令解压缩   tar -zx ...

  8. 函数补充:动态参数,函数嵌套,global与nonlocal关键

    一丶动态参数 1.*args 位置参数,动态传参 def func(*food): print(food) print(func("米饭","馒头"," ...

  9. It is not the destination so much as the journey, they say.

    It is not the destination so much as the journey, they say. 人家说目的地不重要,重要的是旅行的过程.<加勒比海盗>

  10. BUG数量和项目成本

    这篇文章,不是讨论怎么提升程序员的能力避免BUG,因为程序员的能力不足造成的BUG,短期是无法避免的.这里主要探讨的是因为程序员疏忽大意和不良的开发习惯,产生的低级BUG,对项目成本影响. 首先了解下 ...