# 【LeetCode从零单刷】Game of Life

According to the Wikipedia's article: "The Game of Life, also known simply asLife, 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 statelive (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):

1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population..
4. Any dead cell 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 its current state.

1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?

• 0：0-》0
• 1：1-》1
• 2：0-》1
• 3：1-》0

`class Solution {public: int next(int i, int j, vector<vector<int>> board, int cur) { int rowsize = board.size(); int colsize = board[0].size(); int minrow = i > 0 ? (i-1) : 0; int maxrow = i < rowsize - 1 ? (i+1) : (rowsize-1); int mincol = j > 0 ? (j-1) : 0; int maxcol = j < colsize - 1 ? (j+1) : (colsize-1); int neighborlive = 0; for(int a = minrow; a <= maxrow; a++){ for(int b = mincol; b <= maxcol; b++){ if(a == i && b == j) continue; if(board[a][b] == 1 || board[a][b] == 3) neighborlive++; } } if(cur == 1){ if(neighborlive < 2 || neighborlive > 3) return 3; else return 1; } else{ if(neighborlive ==3) return 2; else return 0; } } void gameOfLife(vector<vector<int>>& board) { int rowsize = board.size(); int colsize = board[0].size(); // encoding for(int i = 0; i< rowsize; i++){ for(int j = 0; j< colsize; j++){ board[i][j] = next(i, j, board, board[i][j]); } } // decoding for(int i = 0; i< rowsize; i++){ for(int j = 0; j< colsize; j++){ if (board[i][j] == 3) board[i][j] = 0; if (board[i][j] == 2) board[i][j] = 1; } } }};`