# Middle-题目34：289. Game of Life

131人阅读 评论(0)

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.

1. 若一个活着的细胞周围有少于2个活着的邻居，则它会死于孤独。
2. 若一个活着的细胞周围有2,3个活着的邻居，则它会继续活下去。
3. 若一个活着的细胞周围有3个以上活着的邻居，则它会死于人口过多。
4. 若一个死亡的细胞周围恰有3个活着的细胞，则它会复活，就好像繁殖。

public class Solution {
private final int DEAD = 0;
private final int ALIVE = 1;
public void gameOfLife(int[][] board) {
int m=board.length;
int n=board[0].length;
int[][] nextState = new int[m][n];
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
//Rule 1:Any live cell with fewer than two live neighbors dies, as if caused by under-population.
if(board[i][j] == ALIVE && getNeighbours(board,i,j) <= 1)
//Rule 3:Any live cell with more than three live neighbors dies, as if by over-population.
else if(board[i][j] == ALIVE && getNeighbours(board,i,j) > 3)
//Rule 4:Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
else if(board[i][j] == DEAD && getNeighbours(board,i,j) == 3)
nextState[i][j] = ALIVE;
else
nextState[i][j]=board[i][j];
//System.out.println("i="+i+",j="+j+",neighbours="+getNeighbours(board,i,j,m,n)+",this state="+board[i][j]+",nextState="+nextState[i][j]);
}
}
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
board[i][j]=nextState[i][j];
}
}
}
private int getNeighbours(int[][] board,int i,int j) {
return getState(board,i-1,j-1) + getState(board,i-1,j) + getState(board,i-1,j+1) + getState(board,i,j-1) + getState(board,i,j+1) + getState(board,i+1,j-1) + getState(board,i+1,j) + getState(board,i+1,j+1);
}
private int getState(int[][] board, int i, int j) {
int m = board.length;
int n = board[0].length;
if(i<0 || j<0 || i==m || j==n)
return 0;
else
return board[i][j];
}
}

1ms,beats 13.28%,众数1ms,86.47%
Cmershen的碎碎念：
Discuss中还有一个神算法，有待研读。

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：64684次
• 积分：3289
• 等级：
• 排名：第10725名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论