标签:
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:
Analyse: The problem is how we keep the original state and the updated state. We can use four number to represent four states:
dead_dead: 0
live_dead: 1
dead_live: 2
live_live: 3
Note that we‘d better to use obvious number to stand for the original "live" state and the updated "live" state.
Runtime: 0ms
1 class Solution { 2 private: 3 void live(vector<vector<int> > &board, int i, int j){ 4 int neighbor = 0; 5 for(int m = i - 1; m <= i + 1; m++){ 6 for(int n = j - 1; n <= j + 1; n++){ 7 if(m < 0 || m >= board.size() || n < 0 || n >= board[0].size()) 8 continue; 9 else if(m == i && n == j) 10 continue; 11 else{ 12 if(board[m][n] % 2) 13 neighbor++; //calculate how many live neighbors 14 } 15 } 16 } 17 if(board[i][j]){ 18 if(neighbor < 2 || neighbor > 3) 19 board[i][j] = 1; 20 else 21 board[i][j] = 3; 22 } 23 else{ 24 if(neighbor == 3) 25 board[i][j] = 2; 26 else 27 board[i][j] = 0; 28 } 29 } 30 public: 31 void gameOfLife(vector<vector<int>>& board) { 32 if(board.empty() || board[0].empty()) return; 33 int m = board.size(), n = board[0].size(); 34 35 int dead_dead = 0, live_dead = 1; 36 int dead_live = 2, live_live = 3; 37 for(int i = 0; i < m; i++){ 38 for(int j = 0; j < n; j++){ 39 live(board, i, j); 40 } 41 } 42 for(int i = 0; i < m; i++){ 43 for(int j = 0; j < n; j++){ 44 board[i][j] = board[i][j] < 2 ? 0 : 1; 45 } 46 } 47 } 48 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4941502.html