题目:
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:
链接: http://leetcode.com/problems/game-of-life/
题解:
生命游戏。题目比较长,用extra array做的话比较简单,但要求in-place的话,我们就要使用一些技巧。这里的方法来自yavinci,他的很多Java解法都既精妙又易读,真的很厉害。 我们用两个bit位来代表当前回合和下回合的board。
00代表当前dead
01代表当前live, next dead
10代表当前dead,next live
11代表当前和next都是live
按照题意对当前cell进行更新,全部更新完毕以后, 需要再遍历一遍整个数组,将board upgrade到下一回合, 就是每个cell >>= 1。
Time Complexity - O(mn), Space Complexity - O(1)。
public class Solution { public void gameOfLife(int[][] board) { if(board == null || board.length == 0) { return; } for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[0].length; j++) { int liveNeighbors = getLiveNeighbors(board, i, j); if((board[i][j] & 1) == 1) { if(liveNeighbors >= 2 && liveNeighbors <= 3) { board[i][j] = 3; // change to "11", still live } // else it stays as "01", which will be eleminated next upgrade } else { if(liveNeighbors == 3) { board[i][j] = 2; // change to "10", become live } } } } for(int i = 0; i < board.length; i++) { for(int j = 0; j < board[0].length; j++) { board[i][j] >>= 1; } } } private int getLiveNeighbors(int[][] board, int row, int col) { int res = 0; for(int i = Math.max(row - 1, 0); i <= Math.min(board.length - 1, row + 1); i++) { for(int j = Math.max(col - 1, 0); j <= Math.min(board[0].length - 1, col + 1); j++) { res += board[i][j] & 1; } } res -= board[row][col] & 1; return res; } }
Reference:
https://leetcode.com/discuss/68352/easiest-java-solution-with-explanation
https://leetcode.com/discuss/61912/c-o-1-space-o-mn-time
https://leetcode.com/discuss/61910/clean-o-1-space-o-mn-time-java-solution
原文:http://www.cnblogs.com/yrbbest/p/5040751.html