LeetCode刷题记录——day9

https://leetcode.cn/problems/game-of-life/?envType=study-plan-v2&envId=2024-spring-sprint-100
先创建一个数组,让它比原数组大一圈,然后将其全设为0,在原数组中每有一个1出现,就将其对应位置的新数组的周围全部加一,最后新数组中对应位置的数字就是其周围有多少个活细胞

class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int l1=board.size(),l2=board[0].size();
        int temp_boear[l1+2][l2+2];
        
	    memset(temp_boear,0,sizeof(temp_boear));

        for(int i=1;i<=l1;i++){
            for(int j=1;j<=l2;j++){
                if(board[i-1][j-1]==1){
                    temp_boear[i-1][j-1]++;
                    temp_boear[i][j-1]++;
                    temp_boear[i-1][j]++;
                    temp_boear[i+1][j+1]++;
                    temp_boear[i+1][j]++;
                    temp_boear[i][j+1]++;
                    temp_boear[i+1][j-1]++;
                    temp_boear[i-1][j+1]++;
                }
            }
        }


        for(int i=1;i<=l1;i++){
            for(int j=1;j<=l2;j++){
                if(temp_boear[i][j]<2){
                    board[i-1][j-1]=0;
                }
                if(temp_boear[i][j]>3){
                    board[i-1][j-1]=0;
                }
                if(temp_boear[i][j]==3){
                    board[i-1][j-1]=1;
                }
            }
        }
    }
};
posted @ 2024-03-31 15:23  想成为编程高手的阿曼  阅读(3)  评论(0编辑  收藏  举报