您的位置:首页 > Web前端

289. Game of Life

2016-07-09 22:24 316 查看
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?
按照条件进行就好了,主要是在于怎样in-place处理。
如果一个个更新,会影响到邻居细胞的判断,那么可以先设置额外的一些标记,使用这些标记想达到的目的是一不影响到邻居细胞的判断,二能够在扫描更新的时候识别应该更新为1还是0,这样就满足了不开辟额外空间的要求。

public void gameOfLife(int[][] board)
{
int m=board.length;
if(m<1)
return ;
int n=board[0].length;
if(n<1)
return ;

int[] xoff={-1,-1,-1,0,0,1,1,1};
int[] yoff={1,0,-1,1,-1,1,0,-1};

for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
int cnt=0;
for(int k=0;k<8;k++)
{
int xx=i+xoff[k];
int yy=j+yoff[k];
if(xx>=0&&xx<m&&yy>=0&&yy<n)
if(board[xx][yy]>=1)
cnt++;
}
switch (board[i][j])
{
case 0:
if(cnt==3)
board[i][j]=-1;
break;

case 1:
if(cnt<2||cnt>3)
board[i][j]=2;
break;

default:
break;
}
}

for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
int num=board[i][j];
if(num==-1)
board[i][j]=1;
else if(num==2)
board[i][j]=0;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: