Title Link: https://leetcode.com/problems/game-of-life/
According to the Wikipedia's article: "The Gameof Life, also known simply as Life , is a cellular automa ton devised by the British mathematician John Horton Conway in 1970. "
Given a board with m - n cells, each cell have 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 t He above Wikipedia article):
- Any live cell with fewer than-live neighbors dies, as if caused by under-population.
- Any live cell with a or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population.
- Any dead cells with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given it current state.
Followup:
- Could You solve it in-place? Remember the board needs to be updated at the same time:you cannot update some cells first and then use their update D values to update the other cells.
- In this question, we represent the board using a 2D array. In principle, the board was infinite, which would cause problems when the active area encroaches the border of the array. How would address these problems?
Idea: If you can open extra space will be very simple, is to calculate the number of live around, and then set the next state. If the local can also set a different mark, that is, if the original is dead, the next time to live, set it to 2; If the current is alive the next time you die, set it to 3. Finally in the 2, 3 of the mark is set to 1, 0 is possible.
The code is as follows:
Class Solution {Public:void gameoflife (vector<vector<int>>& board) {if (Board.size () ==0 | | boar D[0].size () ==0) return; int m = board.size (), n = board[0].size (); for (int i = 0; i< m, i++) {for (int J =0; j< N; j + +) {int S1 = 0; if (i-1>=0&& (board[i-1][j]==1| | board[i-1][j]==3)) s1++; if (i-1>=0&&j-1>= 0&& (board[i-1][j-1]==1| | board[i-1][j-1]==3)) s1++; if (i-1>=0&&j+1<n&& (board[i-1][j+1]==1| | board[i-1][j+1]==3)) s1++; if (i+1<m && (board[i+1][j]==1 | | board[i+1][j]==3)) s1++; if (i+1<m&&j-1>=0&& (board[i+1][j-1]==1| | board[i+1][j-1]==3)) s1++; if (i+1<m&&j+1<n&& (board[i+1][j+1]==1| | board[i+1][j+1]==2)) s1++; if (j-1>=0&& (board[i][j-1]==1 | | board[i][j-1]==3)) s1++; IfJ+1 < n && (board[i][j+1] = = 1 | | board[i][j+1]==3)) s1++; if (board[i][j]==1 && (S1 < 2| | s1>3)) Board[i][j] = 3; else if (board[i][j]==0 && S1 = = 3) board[i][j] = 2; }} for (int i = 0; i< m; i++) for (Int J =0; j< N; j + +) if (board[i][j] = = 2) BOARD[I][J] = 1; else if (board[i][j] = = 3) Board[i][j] = 0; }};
[Leetcode] 289. Game of life Problem solving report