C++ O(1) Space Solution. No bitwise operations.


  • 0

    if next generation lives: 10 or 11
    if next generation dies : 0 or 1

    class Solution {
    public:
        void gameOfLife(vector<vector<int>>& board) {
            for (int i = 0; i < board.size(); i++) {
                for (int j = 0; j < board[0].size(); j++) {
                    int cnt = countNeighbors(i, j, board);
                    if (cnt == 3 || (cnt == 2 && board[i][j] == 1)) board[i][j] += 10;
                }
            }
            
            updateBoard(board);
        }
        
        int countNeighbors(int i, int j, const vector<vector<int>>& board) {
            int cnt = 0;
            for (int r = max(i - 1, 0); r <= min(i + 1, (int)board.size() - 1); r++) {
                for (int c = max(j - 1, 0); c <= min(j + 1, (int)board[0].size() - 1); c++) {
                    if (i != r || j != c) cnt += board[r][c] % 10;
                }
            }
            return cnt;
        }
        
        void updateBoard(vector<vector<int>>& board) {
            for (int i = 0; i < board.size(); i++) {
                for (int j = 0; j < board[0].size(); j++) {
                    board[i][j] = board[i][j] / 10;
                }
            }
        }
    };
    

Log in to reply
 

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