您的位置:首页 > Web前端

LeetCode:Game of Life

2016-01-14 09:48 197 查看
题目描述:

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、生成和给定数组相同大小的新的数组popu,用来统计每个数值对应的人的邻居个数。

2、根据每个人的邻居个数,重新计算原来的人是死是活。

若原来的人是活的,邻居个数等于2或3, 这个人活着,否则死去。

若原来的人是死的,邻居个数等于3,这个人活过来,否则仍然死的。

代码:

class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
vector<int> board0 = board[0];
int n =board0.size();
vector<vector<int>> popu;
for(int i = 0; i < m; i ++)
{
vector<int> popSingle;
bool iDecrese = i - 1 >= 0;
bool iIncrese = i + 1 < m;
for(int j = 0; j < n; j ++)
{
int pop = 0;
bool jDecrese = j - 1 >= 0;
bool jIncrease = j + 1 < n;
if(iDecrese)
{
pop += board[i - 1][j] == 1;
if(jDecrese)
pop += board[i - 1][j - 1] == 1;
if(jIncrease)
pop += board[i - 1][j + 1] == 1;
}
if(iIncrese)
{
pop += board[i + 1][j] == 1;
if(jDecrese)
pop += board[i + 1][j - 1] == 1;
if(jIncrease)
pop += board[i + 1][j + 1] == 1;
}
if(jDecrese)
pop += board[i][j - 1] == 1;
if(jIncrease)
pop += board[i][j + 1] == 1;
popSingle.push_back(pop);
}
popu.push_back(popSingle);
}
for(int i = 0; i < m; i ++)
{
for(int j = 0; j < n; j ++)
{
int pri = board[i][j];
int bour = popu[i][j];
board[i][j] = ((pri == 1) && (bour == 2 || bour == 3)) || ((pri == 0) && (bour == 3)) ? 1: 0;
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: