class Solution { public: void gameOfLife(vector<vector<int>>& board) { queue<int> temp_state; int row = board.size(); int i,j; if(row < 1) return; int col = board[0].size(); if(col <1) return; for(i=0;i<row;i++) for(j=0;j<col;j++){ int state_i_j = next_state(board,i,j); temp_state.push(state_i_j); if((j == col-1)) { //每行最后一个元素 更新 if((i>=1)){ //如果不是第一行,更新前一行 for(int z=0;z<col;z++){ board[i-1][z] = temp_state.front(); temp_state.pop(); } } if((i==row-1)){ //如果是最后一行,更新当前行 for(int z=0;z<col;z++){ board[i][z] = temp_state.front(); temp_state.pop(); } } } } } int next_state(vector<vector<int>>& board,int i,int j){ int sum = 0; int row = board.size(); int col = board[0].size(); if(board[i][j] == 1){ if(i-1 >=0){ if(j-1>=0 && board[i-1][j-1] == 1) sum++; if(board[i-1][j] == 1) sum++; if(j+1<col && board[i-1][j+1] == 1) sum++; } if(i+1 < row){ if(j-1>=0 && board[i+1][j-1] == 1) sum++; if(board[i+1][j] == 1) sum++; if(j+1<col && board[i+1][j+1] == 1) sum++; } if(j-1>=0 && board[i][j-1] == 1) sum++; if(j+1< col && board[i][j+1] == 1) sum++; if(sum==2 || sum ==3) return 1; return 0; } if(board[i][j] == 0){ if(i-1 >=0){ if(j-1>=0 && board[i-1][j-1] == 1) sum++; if(board[i-1][j] == 1) sum++; if(j+1<col && board[i-1][j+1] == 1) sum++; } if(i+1 < row){ if(j-1>=0 && board[i+1][j-1] == 1) sum++; if(board[i+1][j] == 1) sum++; if(j+1<col && board[i+1][j+1] == 1) sum++; } if(j-1>=0 && board[i][j-1] == 1) sum++; if(j+1< col && board[i][j+1] == 1) sum++; if(sum ==3) return 1; return 0; } } };