标签:
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):
Write a function to compute the next state (after one update) of the board given its current state.
Follow up:
位运算(bit manipulation)
由于细胞只有两种状态0和1,因此可以使用二进制来表示细胞的生存状态
更新细胞状态时,将细胞的下一个状态用高位进行存储
全部更新完毕后,将细胞的状态右移一位
To solve it in place, we use 2 bits to store 2 states:
[2nd bit, 1st bit] = [next state, current state]
- 00 dead (current) -> dead (next)
- 01 live (current) -> dead (next)
- 10 dead (current) -> live (next)
- 11 live (current) -> live (next)
In the beginning, every 2nd state is 0
; when next becomes alive change 2nd bit to 1
:
nbs < 2 || nbs > 3
(we don‘t need to care!)nbs >= 2 && nbs <= 3
nbs == 3
To get this state, we simple do:
board[i][j] & 1
To get next state, we simple do:
board[i][j] >> 1
Java code:
public class Solution { public void gameOfLife(int[][] board) { if(board == null || board.length == 0) { return; } int m = board.length, n = board[0].length; // In the beginning, every 2nd bit is 0; // So we only need to care about when 2nd bit will become 1. for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { int lives = liveNeighbors(board, m, n, i , j); if((board[i][j] & 1) == 1 && (lives >= 2 && lives <= 3)) { board[i][j] = 3; //Make the 2nd bit 1: 01----> 11 }else if ((board[i][j] & 1) == 0 && (lives == 3)) { board[i][j] = 2; // Make the 2nd bit 1: 00-----> 10 } } } for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { board[i][j] >>= 1; //Get the 2nd state } } } private int liveNeighbors(int[][]board, int m, int n, int i , int j){ int lives = 0; int[][] d= {{1,-1},{1,0},{1,1},{0,-1},{0,1},{-1,-1},{-1,0},{-1,1}}; for(int k = 0; k < 8; k++) { int x = d[k][0] + i; int y = d[k][1] + j; if( x < 0 || x >= m || y < 0 || y >= n){ continue; } if((board[x][y] & 1) == 1) { lives++; } } return lives; } }
Reference:
1. https://leetcode.com/discuss/68352/easiest-java-solution-with-explanation
2. https://leetcode.com/discuss/62038/c-ac-code-o-1-space-o-mn-time
3. http://bookshadow.com/weblog/2015/10/04/leetcode-game-life/
标签:
原文地址:http://www.cnblogs.com/anne-vista/p/4960910.html