Simple in-place 0ms 16-line c++


  • 2
    M
    class Solution {
    public:
        void gameOfLife(vector<vector<int>>& board) {
            /* idea: if cell's live neighbor is 7, and cell is 1, then cell becomes 7*10+1 = 71. 
               Later we can get live count by 71/10, and cell value by 71%10. */
    
            int dx[] = {0, 1, 1, 1, 0, -1, -1, -1};
            int dy[] = {1, 1, 0, -1, -1, -1, 0, 1};
            int m=board.size(), n=board[0].size();
            
            for (int j=0; j<m; j++)
                for (int i=0; i<n; i++) {
                    int live=0;
                    for (int d=0; d<8; d++)
                        if (0<=i+dx[d] && i+dx[d]<n && 0<=j+dy[d] && j+dy[d]<m && (board[j+dy[d]][i+dx[d]]%10))
                            live++;
                    board[j][i] += (live*10);
                }
            
            for (int j=0; j<m; j++)
                for (int i=0; i<n; i++) {
                    int live = board[j][i]/10, &cell = board[j][i];
                    cell = cell%10;
                    if (live<2) cell=0;
                    if (live>3) cell=0;
                    if (live==3 && cell==0) cell=1;
                }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.