LeetCode(289)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):
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?
分析
基于一个生命游戏的题目,游戏介绍。
生死判断条件:
- 一個活的格子若只有一個或沒有鄰居, 在下一秒將因寂寞而亡;
- 一個活的格子若有四個或四個以上的鄰居, 在下一秒將因拥擠而亡;
- 一個活的格子若有二個或三個鄰居, 在下一秒將継續活著;
- 一個死的格子若有三個鄰居, 在下一秒將活過來;
题目要求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;
}
};
LeetCode(289)Game of Life的更多相关文章
- LeetCode(275)H-Index II
题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...
- LeetCode(220) Contains Duplicate III
题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...
- LeetCode(154) Find Minimum in Rotated Sorted Array II
题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...
- 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 ...
- LeetCode(116) Populating Next Right Pointers in Each Node
题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...
- 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 ...
- 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 ...
- 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 ...
- Leetcode(1)两数之和
Leetcode(1)两数之和 [题目表述]: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标.你可以假设每种输入只会对应一 ...
随机推荐
- windows/Linux下设置ASP.Net Core开发环境并部署应用
10分钟学会在windows/Linux下设置ASP.Net Core开发环境并部署应用 创建和开发ASP.NET Core应用可以有二种方式:最简单的方式是通过Visual Studio 2017 ...
- CellSet 遍历
CellSet 结构: 查询MDX: SELECT NON EMPTY {{ {{ {{ {{ {{ AddCalculatedMembers([店铺.店铺ID].[店铺ID].Members)}} ...
- 项目协作管理平台-teambition和tapd--深度体验
一.分析目的 通过分析2B产品中的团队协作管理软件的对比分析,用于为公司团队协作软件的选型做产考. 二.竞品归属市场概况 2.1.目标用户群及需求 主要面向企业用户,用于解决企业不同地域以及不同职 ...
- WPF 模拟Button按钮事件触发
this.Submit.AddHandler(Button.ClickEvent, new RoutedEventHandler(this.Submit_Click)); //这种是无效的方法 thi ...
- GoDaddy网站程序根目录 网站文件上传到虚拟主机哪个目录
用的linux虚拟主机,网站根目录为public_html,(window主机的目录为httpdocs)我们需要把本地做好的网站上传到此目录下 cPanel控制面板 - 文件管理器 - public_ ...
- elasticsearch 2.4 windows版jvm内存设置
本文编写目的是因为网上有很多es修改内存配置的文章,方法也各有不同,但在我的情况下(es 2.4 windows版)发现很多方法都是无效的,有效只有以下方法 第一个是xms,第二个是xmx
- 【extjs6学习笔记】0.1 准备:基础概念(02)
Ext 类 Ext 是一个全局单例的对象,在 Sencha library 中它封装了所有的类和许多实用的方法.许多常用的函数都定义在 Ext 对象里.它还提供了像其他类中一些频繁使用的方法的快速调用 ...
- Jenkins系列——使用Dashboard View分类展示作业
1.目标 创建的作业多了,在一个视图中展示多有不便.因此需要使用 Dashboard View 将作业按照后缀进行分类展示. 如下图,可以按照后缀添加CODE,TEST和OTHER视图. 2.环境说明 ...
- 多段图动态规划dp
多段图问题是DP的基础题目.大体的意思是有一个赋权有向图,其顶点集被分为几个子集.求经过每个子集从源点到终点的最短路径 import java.util.ArrayList; import java. ...
- JSONPath - XPath for JSON
http://goessner.net/articles/JsonPath/ [edit] [comment] [remove] |2007-02-21| e1 # JSONPath - XPath ...