-
Notifications
You must be signed in to change notification settings - Fork 1
/
289. Game of Life.cpp
39 lines (39 loc) · 1.26 KB
/
289. Game of Life.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
int numLiveNeighbors(vector<vector<int>>& board, int i, int j) {
int n = board.size();
int m = board[0].size();
int ans = 0;
for(int s = i-1; s <= i+1; s++) {
for(int e = j-1; e <= j+1; e++) {
if(s == i && e == j) continue;
if((s >= 0 && s < n) && (e >= 0 && e < m) && (board[s][e] >= 1)) ans++;
}
}
return ans;
}
void gameOfLife(vector<vector<int>>& board) {
int n = board.size();
int m = board[0].size();
int neighbour;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(board[i][j] == 1) {
neighbour = numLiveNeighbors(board, i, j);
if(neighbour == 2 || neighbour == 3) board[i][j]++;
}
else {
neighbour = numLiveNeighbors(board, i, j);
if(neighbour == 3) board[i][j]--;
}
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(board[i][j] == -1 || board[i][j] == 2)
board[i][j] = 1;
else board[i][j] *= 0;
}
}
}
};