Game of Life Solutions in C++
Number 289
Difficulty Medium
Acceptance 54.6%
Link LeetCode
Other languages —
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/game-of-life/// Author : Hao Chen// Date : 2019-03-20class Solution {public:// the problem here is we need store two states in one cell,// one is the original state, another is the new state// So, we could store the state into the bit.// - Old State: the first bit from the right// - New State: the second bit from the rightvoid liveCheck(vector<vector<int>>& board, int r, int c) {int cnt = 0;for (int i=r-1; i<=r+1; i++) {if (i < 0 || i>=board.size()) continue;for (int j=c-1; j<=c+1; j++) {if (j<0 || j>=board[0].size() || (i==r && j==c)) continue;if ( board[i][j] & 1 ) cnt++;}}//live -> die//if (board[r][c]==1 && (cnt < 2 || cnt > 3)) board[r][c] = 1;//live -> liveif ( board[r][c] == 1 && (cnt == 2 || cnt == 3) ) board[r][c] = 3;//die -> liveif ( board[r][c] == 0 && cnt == 3 ) board[r][c] = 2;}void gameOfLife(vector<vector<int>>& board) {for (int i=0; i<board.size(); i++) {for (int j=0; j<board[0].size(); j++) {liveCheck(board, i, j);}}for (int i=0; i<board.size(); i++) {for (int j=0; j<board[0].size(); j++) {board[i][j] >>= 1;}}}};