leetcode补全计划-20180816

  1. 289 Game of Life
    输入:vector>& board
    输出:void
    题意:生存游戏。0表示死亡,1表示存活。当活细胞周围的活细胞数量少于两个或者大于三个的时候,该细胞死去。当死细胞周围活细胞的数量恰好等于3个的时候,该细胞复活。要求返回下一时刻的状态。要求in-place。
    思路:使用自动机的思想,首先建立4个状态:
    状态0:当前时刻0,下一时刻0
    状态1:当前时刻1,下一时刻1
    状态2:当前时刻1,下一时刻0
    状态3:当前时刻0,下一时刻1
    在此基础上,我们可以将现在的0-1按照情况变换为0-3,全部变换完毕之后可以使用除2取余的方式进行解码。
class Solution {
public:
    void gameOfLife(vector>& board) {
        int m = board.size();
        int n = board[0].size();
        for(int i = 0;i < m;++ i){
            for(int j = 0;j < n;++ j){
                int lives = 0;
                if(i > 0 && (board[i - 1][j] == 1 || board[i - 1][j] == 2)) lives ++;
                if(j > 0 && (board[i][j - 1] == 1 || board[i][j - 1] == 2)) lives ++;
                if(i < m - 1 && (board[i + 1][j] == 1 || board[i + 1][j] == 2)) lives ++;
                if(j < n - 1 && (board[i][j + 1] == 1 || board[i][j + 1] == 2)) lives ++;
                if(i > 0 && j > 0) lives += board[i - 1][j - 1] == 1 || board[i - 1][j - 1] == 2 ? 1 : 0;
                if(i > 0 && j < n - 1) lives += board[i - 1][j + 1] == 1 || board[i - 1][j + 1] == 2 ? 1 : 0;
                if(i < m - 1 && j > 0) lives += board[i + 1][j - 1] == 1 || board[i + 1][j - 1] == 2 ? 1 : 0;
                if(i < m - 1 && j < n - 1) lives += board[i + 1][j + 1] == 1 || board[i + 1][j + 1] == 2 ? 1 : 0;
                if(board[i][j] == 0 && lives == 3) board[i][j] = 3;
                else if(board[i][j] == 1 && (lives < 2 || lives > 3)) board[i][j] = 2;
            }
        }
        for(int i = 0;i < m;++ i) for(int j = 0;j < n;++ j) board[i][j] %= 2;
    }
};

你可能感兴趣的:(leetcode补全计划-20180816)