-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path289-game-of-life.cpp
48 lines (44 loc) · 1.53 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
40
41
42
43
44
45
46
47
48
class Solution {
public:
void process(vector<vector<int>>& board, int m, int n, int i, int j, vector<vector<int>>& neighbors) {
int aliveNeighbors = 0;
for (vector<int>& N : neighbors) {
int newI = i + N[0];
int newJ = j + N[1];
if (newI >= 0 && newI < m && newJ >= 0 && newJ < n && (board[newI][newJ] == 1 || board[newI][newJ] == -2)) {
aliveNeighbors++;
}
}
if (board[i][j] == 0) {
if (aliveNeighbors == 3) {
board[i][j] = -1;
}
} else {
if (aliveNeighbors < 2 || aliveNeighbors > 3) {
board[i][j] = -2;
}
}
}
void gameOfLife(vector<vector<int>>& board) {
// 0, 1 remain unchancged
// 0 -> 1 encode with -1
// 1 -> 0 encode with -2
int m = board.size();
int n = board[0].size();
vector<vector<int>> neighbors = {{-1, 0}, {-1, -1}, {-1, 1}, {0, -1}, {0, 1}, {1, 0}, {1, -1}, {1, 1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
process(board, m, n, i, j, neighbors);
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == -1) {
board[i][j] = 1;
} else if (board[i][j] == -2) {
board[i][j] = 0;
}
}
}
}
};