---
# System prepended metadata

title: LeetCode - 289. Game of Life
tags: [LeetCode]

---

---
title: LeetCode - 289. Game of Life
tags: LeetCode
description: by cpp
---
# [LeetCode] 289. Game of Life
input : 一個陣列
output : 根據遊戲規則調整陣列，沒有回傳

遊戲規則如下:
1. 活細胞: 少於兩個活鄰居，死亡
2. 活細胞: 有兩或三活鄰居，存活
3. 活細胞: 超過三個活鄰居，死亡
4. 死細胞: 剛好三個活鄰居，復活


所以只要用board .at(i) .at(j)
去環顧周圍(8個鄰居)，並計算活著的細胞，
並依照遊戲規則調整細胞狀態就可以輕鬆秒殺

```cpp=
class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        vector<vector<int>> result;
        int row = board.size();
        int col = board[0].size();
        vector<int> temp;
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                int live_count=get_live(i,j,board);
                if(board.at(i).at(j)==1){
                    
                    if(live_count<2){//規則1
                        temp.push_back(0);
                    }else if(live_count==2 || live_count==3){//規則2
                        temp.push_back(1);
                    }else if(live_count>3){//規則3
                        temp.push_back(0);
                    }
                    
                }else{
                    if(live_count==3){//規則4
                        temp.push_back(1);
                    }else{
                        temp.push_back(0);
                    }
                }
                
            }
            result.push_back(temp);
            temp.clear();
        }
        board = result;//把換好的直接換到答案
    }
    //因為會有out_of_range 的問題 所以用try catch來解決
    //太長了 所以又另外包成一個函式
    int get_live(int x,int y,vector<vector<int>>& board){
        int count_alive=0;
        try{
            count_alive+=board.at(x-1).at(y-1);
        }catch(out_of_range& oor){
            cout << "";
        }
        try{
            count_alive+=board.at(x-1).at(y);
        }catch(out_of_range& oor){
            cout << "";
        }
        try{
            count_alive+=board.at(x-1).at(y+1);
        }catch(out_of_range& oor){
            cout << "";
        }
        try{
            count_alive+=board.at(x).at(y-1);
        }catch(out_of_range& oor){
            cout << "";
        }
        try{
            count_alive+=board.at(x).at(y+1);
        }catch(out_of_range& oor){
            cout << "";
        }
        try{
            count_alive+=board.at(x+1).at(y-1);
        }catch(out_of_range& oor){
            cout << "";
        }
        try{
            count_alive+=board.at(x+1).at(y);
        }catch(out_of_range& oor){
            cout << "";
        }
        try{
            count_alive+=board.at(x+1).at(y+1);
        }catch(out_of_range& oor){
            cout << "";
        }
        return count_alive;
        
    }
};
```

{%hackmd theme-dark %}