Leetcode 289 Solution

This article provides solution to leetcode question 289 (game-of-life)

https://leetcode.com/problems/game-of-life

Solution

class Solution { public: void gameOfLife(vector<vector<int>>& board) { int m = board.size(); if (m == 0) return; int n = board[0].size();
const int dx[8] = {-1, -1, -1, 0, 1, 1, 1, 0}; const int dy[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int cnt = 0;
for (int k = 0; k < 8; k++) { if (i + dy[k] < 0 || i + dy[k] >= m) continue;
if (j + dx[k] < 0 || j + dx[k] >= n) continue;
if (board[i + dy[k]][j + dx[k]] & 1) cnt++; }
if (((board[i][j] & 1) == 1) && cnt >= 2 && cnt <= 3) board[i][j] |= 2; else if (((board[i][j] & 1) == 0) && cnt == 3) board[i][j] |= 2; } }
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] = board[i][j] >> 1; } } } };