0ms solution...easy to understand


  • 0
    A
    class Solution {
    public:
        void gameOfLife(vector<vector<int>>& board) {
            int r = board.size();
            if(r == 0)
                return;
            int xmov[] = {1, -1, 0, 0, 1, 1, -1, -1};
            int ymov[] = {0, 0, 1, -1, 1, -1, 1, -1};
            int i,j,k,x,y, cnt;
            int c = board[0].size();
            for (i = 0; i < r; i++) {
                for(j = 0; j < c; j++) {
                    cnt = 0;
                    for(k = 0; k < 8; k++) {
                        x = i + xmov[k];
                        y = j + ymov[k];
                        if(x >= 0 && x < r && y >= 0 && y < c) {
                            if(board[x][y] == 1 || board[x][y] == -5)
                                cnt++;
                        }
                    }
                    if(board[i][j] == 1) {
                        if(cnt < 2) {
                            board[i][j] = -5;
                        }
                        else if(cnt > 3) {
                            board[i][j] = -5;
                        }
                    } else {
                        if(cnt == 3)
                            board[i][j] = 5;
                    }
                }
            }
             for (i = 0; i < r; i++) {
                for(j = 0; j < c; j++) {
                    if(board[i][j] == -5)
                        board[i][j] = 0;
                    if(board[i][j] == 5)
                        board[i][j] = 1;
                }
             }
        }
    };

Log in to reply
 

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