标签:
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:
思路:要求 in-place ,所以要区分三种变化状态 1->0,1->1,0->1,将三种状态分别用-1/-2/-3三个状态值来表示
第一次遍历时,先判断当前cell的转换状态,且将cell值置为对应状态值,在后面的遍历中根据状态值则可推断出原始值,进而判断转换状态。
第二次遍历,则将状态值置为变换后的值
public class S289 { public void gameOfLife(int[][] board) { int m = board.length,n = board[0].length; for (int i = 0;i < m;i++) { for (int j = 0;j < n;j++) { int liveCount = 0; for (int k = i-1;k <= i+1;k++) { for (int l = j-1;l <= j+1;l++) { if(k < 0 || l < 0 || k > m-1 || l > n-1 || (k == i && l == j)) continue; liveCount += getRealNum(board[k][l]); } } if (board[i][j] == 1) { if (liveCount <2 || liveCount >3 ) { board[i][j] = -1; } else { board[i][j] = -2; } } else { if (liveCount == 3) { board[i][j] = -3; } } } } for (int i = 0;i < m;i++) { for (int j = 0;j < n;j++) { if (board[i][j] == -2 || board[i][j] == -3) board[i][j] = 1; else if (board[i][j] == -1) board[i][j] = 0; } } } public static int getRealNum(int i){ if(i == -1 || i == -2) return 1; else if (i == -3) { return 0; } return i; } public static void main(String[] args) { S289 s = new S289(); int [][]b = {{1}}; s.gameOfLife(b); } }
标签:
原文地址:http://www.cnblogs.com/fisherinbox/p/5427612.html