标签:
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:
这题的关键在于合适的编码。我们用两位来代表每个cell的状态。
after prev
1 0 以前是dead,经过一次update后为live
1 1 以前是live,经过一次update后为live
0 1 以前是live,经过一次update后为dead
0 0 以前是dead,经过一次update后为dead
由此我们看到取得prev位可以用%操作,取得after位可以用/操作。
因此我们遍历两遍2维数组。第一遍是将所有元素编码成上述两位形式。第二遍是除法操作,得到after。
Time complexity O(mn), space cost O(1)
1 public class Solution { 2 public void gameOfLife(int[][] board) { 3 int[][] directions = {{-1,0},{1,0},{0,1},{0,-1},{-1,-1},{-1,1},{1,-1},{1,1}}; 4 int m = board.length, n = board[0].length; 5 for (int i = 0; i < m; i++) { 6 for (int j = 0; j < n; j++) { 7 int prev = board[i][j]; 8 int liveCount = 0, deadCount = 0; 9 for (int k = 0; k < 8; k++) { 10 int newX = i + directions[k][0]; 11 int newY = j + directions[k][1]; 12 if (newX < 0 || newX >= m || newY < 0 || newY >= n) { 13 continue; 14 } 15 if (board[newX][newY] % 2 == 1) { 16 liveCount++; 17 } 18 } 19 if (prev == 0) { 20 if (liveCount == 3) { 21 board[i][j] += 2; 22 } 23 } else { 24 if (liveCount == 2 || liveCount == 3) { 25 board[i][j] += 2; 26 } 27 } 28 } 29 } 30 for (int i = 0; i < m; i++) { 31 for (int j = 0; j < n; j++) { 32 board[i][j] = board[i][j] / 2; 33 } 34 } 35 } 36 }
标签:
原文地址:http://www.cnblogs.com/ireneyanglan/p/4946686.html