To save space, we can extend some composite states to include previous states. For example, if a cell’s previous state was 0, but after update it becomes 1, we can define a composite state 2. Then when we see 2, we know both that the cell is currently alive and that it was dead before.
classSolution { public: voidget_cnt(vector<vector<int> > &board, int &live_cell_cnt, int i, int j) { int m = board.size(), n = board[0].size(); live_cell_cnt = 0;
// Up if (i > 0) { if (board[i - 1][j] == 1) { live_cell_cnt++; } } // Down if (i < m - 1) { if (board[i + 1][j] == 1) { live_cell_cnt++; } } // Left if (j > 0) { if (board[i][j - 1] == 1) { live_cell_cnt++; } } //Right if (j < n - 1) { if (board[i][j + 1] == 1) { live_cell_cnt++; } } // Top-left corner if (i > 0 && j > 0) { if (board[i - 1][j - 1] == 1) { live_cell_cnt++; } } // Top-right corner if (i > 0 && j < n - 1) { if (board[i - 1][j + 1] == 1) { live_cell_cnt++; } } // bottom left corner if (i < m - 1 && j > 0) { if (board[i + 1][j - 1] == 1) { live_cell_cnt++; } } // bottom right corner if (i < m - 1 && j < n - 1) { if (board[i + 1][j + 1] == 1) { live_cell_cnt++; } } } voidgameOfLife(vector<vector<int> > &board) { vector<vector<int> > original(board); int m = board.size(), n = board[0].size(); int i, j, live_cell_cnt; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { get_cnt(original, live_cell_cnt, i, j); if (original[i][j] == 1) { if (live_cell_cnt < 2) { // If a live cell has fewer than two live neighbors among its eight surrounding positions, it dies; board[i][j] = 0; } elseif (live_cell_cnt == 2 || live_cell_cnt == 3) { // If a live cell has two or three live neighbors among its eight surrounding positions, it survives; board[i][j] = 1; } else { // If a live cell has more than three live neighbors among its eight surrounding positions, it dies; board[i][j] = 0; } } else { if (live_cell_cnt == 3) { // If a dead cell has exactly three live neighbors among its eight surrounding positions, it becomes alive; board[i][j] = 1; } } } } } };