1+ class Solution {
2+ public:
3+ int countLiveNeighbors (const vector<vector<int >>& board, int i, int j, int m, int n) {
4+ int count = 0 ;
5+ // edgecases for rows
6+ if (i > 0 ){ // consider [i-1][j-1], [i-1][j], [i-1][j+1]
7+ if (j > 0 && board[i - 1 ][j - 1 ]) ++count; // prev col prev row
8+ if (board[i - 1 ][j]) ++count; // prev row same col
9+ if (j + 1 < n && board[i - 1 ][j + 1 ]) ++count; // prev row next col
10+ }
11+
12+ if (i + 1 < m){ // consider [i+1][j-1], [i+1][j], [i+1][j+1]
13+ if (j > 0 && board[i + 1 ][j - 1 ]) ++count; // next row prev col
14+ if (board[i + 1 ][j]) ++count; // next row same col
15+ if (j + 1 < n && board[i + 1 ][j + 1 ]) ++count; // next row next col
16+ }
17+
18+ // edge cases for cols
19+ if (j > 0 && board[i][j - 1 ]) ++count; // same row prev col
20+ if (j + 1 < n && board[i][j + 1 ]) ++count; // same row next col
21+
22+ return count;
23+ }
24+
25+ void gameOfLife (vector<vector<int >>& board) {
26+ int num_rows = board.size ();
27+ int num_cols = board[0 ].size ();
28+ vector<vector<int >> res (num_rows, vector<int >(num_cols, 0 ));
29+ for (int i = 0 ; i < num_rows; ++i) {
30+ for (int j = 0 ; j < num_cols; ++j) {
31+ int count = countLiveNeighbors (board, i, j, num_rows, num_cols);
32+ if (board[i][j] == 0 ) {
33+ if (count == 3 )
34+ res[i][j] = 1 ;
35+ } else {
36+ if (count == 2 || count == 3 )
37+ res[i][j] = 1 ;
38+ }
39+ }
40+ }
41+ board = res;
42+ return ;
43+ }
44+ };
0 commit comments