Problem
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?
Solution
class Solution {
public void gameOfLife(int[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) return;
//how to get to neighbors for board[i][j] -> use int[8][2] to store offset in 8 directions
int[][] directions = {{-1,-1},{-1,0},{-1,1},{0,1},{0,-1},{1,-1},{1,0},{1,1}};
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
int lives = 0;
for (int k = 0; k < directions.length; k++) {
int x = i+directions[k][0];
int y = j+directions[k][1];
if (x >= 0 && x < board.length &&
y >= 0 && y < board[0].length &&
board[x][y]%2 == 1) lives++;
}
if (board[i][j]%2 == 1) {
if (lives == 2 || lives == 3) board[i][j] += 2;
} else {
if (lives == 3) board[i][j] += 2;
}
}
}
//after +2 operations for all live cells, the dying cells still hold 1 or 0
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
//eliminate 1s and 0s to 0, 3s and 2s to 1
board[i][j] >>= 1;
}
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。