**Leetcode 289. Game of Life

https://leetcode.com/problems/game-of-life/description/

有意思的题

算是状压存储状态

int xp[] = { -1,1,0,0, -1,1,-1,1 };
int yp[] = { 0,0,1,-1, -1,1,1,-1 };
class Solution {
public:
    void gameOfLife(vector>& board) {
        if (board.empty() || board[0].empty() ) return;
        for (int i = 0; i < board.size(); i++) {
            for (int j = 0; j < board[0].size(); j++) {
                int cnt = 0;
                for (int ii = 0; ii < 8; ii++) {
                    int xx = i + xp[ii];
                    int yy = j + yp[ii];
                    if ( xx >=0 && xx < board.size() && yy >= 0 && yy < board[0].size() ) {
                        cnt += board[xx][yy] % 2;
                    }
                }
                if (cnt < 2) {
                    board[i][j] = board[i][j] ? 1 : 0; 
                } else {
                    if (cnt < 4) {
                        if (cnt == 3 && board[i][j] == 0) board[i][j] = 2;
                        else board[i][j] = board[i][j] ? 3 : 0;
                    } else {
                        if (cnt > 3) {
                            board[i][j] = board[i][j] ? 1 : 0;
                        }
                    }
                }
            }
        }
        
        for (int i = 0; i < board.size(); i++) {
            for (int j = 0; j < board[0].size(); j++) {
                board[i][j] = (board[i][j] & 2) >> 1;
            }
        }
        
    }
};

 

 

你可能感兴趣的:(**Leetcode 289. Game of Life)