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. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.
Example:
Input:
[
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
Output:
[
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]
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?
解题思路
- 先对原二维数组进行预处理:将最后一位作为当前生命是否存活的标识位,第 2 到 5 位作为周边生命的计数
- 根据预处理的结果和生存规则,更新每个生命的新状态。
AC 代码
func countNeighbors(board [][]int, x, y int) int{
cnt := 0
dirs := [][]int{
{-1, -1}, // 左上
{-1, 0}, // 正上
{-1, 1}, // 右上
{ 0, -1}, // 左边
{ 0, 1}, // 右边
{ 1, -1}, // 左下
{ 1, 0}, // 正下
{ 1, 1}, // 右下
}
for i := 0; i < len(dirs); i++{
tx := x + dirs[i][0]
ty := y + dirs[i][1]
if tx < 0 || tx >= len(board) || ty < 0 || ty >= len(board[x]){
continue
}
cnt += (board[tx][ty] & 1)
}
return cnt
}
func gameOfLife(board [][]int) {
const countFlag int = (0xf << 1)
// 1. 计算每一个生命周边的生命数(最后一位标识当前位置是否有生命)
for i := 0; i < len(board); i++{
for j := 0; j < len(board[i]); j++{
board[i][j] |= (countNeighbors(board, i, j) << 1)
}
}
// 2. 计算每一个生命的存活情况
for i := 0; i < len(board); i++{
for j := 0; j < len(board[i]); j++{
neighborsNum := ((board[i][j] & countFlag) >> 1)
// 原本活着的生命
if (board[i][j] & 1) == 1 {
if neighborsNum < 2 || neighborsNum > 3 { // dead
board[i][j] = 0
}else if neighborsNum == 2 || neighborsNum == 3{ // alive
board[i][j] = 1
}
} else if (board[i][j] & 1) == 0 { // 原本死了的生命
if neighborsNum == 3 { // reproduction
board[i][j] = 1
} else { // keep dead
board[i][j] = 0
}
}
}
}
}