Game of Life

LeetCode #289


Description:

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):

Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two 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 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.

Follow up:
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.

Example:

Note

Idea:

0 : 上一轮是0,这一轮过后还是0
1 : 上一轮是1,这一轮过后还是1
3 : 上一轮是1,这一轮过后变为0
2 : 上一轮是0,这一轮过后变为1

Time O(n2), Space O(1)

Code:

class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m=board.size();
        int n=board[0].size();

        vector<pair<int, int>> move={{-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}};

        // 先扫一遍,记录状态
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                int count=0;
                for(auto e: move){
                    int next_x=e.first+i;
                    int next_y=e.second+j;
                    if(next_x>=0&&next_x<m&&next_y>=0&&next_y<n&&board[next_x][next_y]%2==1){
                        count++;
                    }
                }
                if(board[i][j]==1){
                    if(count<2||count>3) board[i][j]=3;
                }
                else{
                    if(count==3) board[i][j]=2;
                }
            }
        }

        //再扫一遍,该变0的变0,该变1的变1
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(board[i][j]==2) board[i][j]=1;
                if(board[i][j]==3) board[i][j]=0;
            }
        }
    }
};

results matching ""

    No results matching ""