-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0289_gameOfLife.cc
74 lines (65 loc) · 1.75 KB
/
Problem_0289_gameOfLife.cc
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
void gameOfLife(vector<vector<int>> &board)
{
int N = board.size();
int M = board[0].size();
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
int nb = neighbors(board, i, j);
if (nb == 3 || (board[i][j] == 1 && nb == 2))
{
set(board, i, j);
}
}
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
board[i][j] = get(board, i, j);
}
}
}
int neighbors(vector<vector<int>> &board, int i, int j)
{
int count = 0;
count += ok(board, i - 1, j - 1) ? 1 : 0;
count += ok(board, i - 1, j) ? 1 : 0;
count += ok(board, i - 1, j + 1) ? 1 : 0;
count += ok(board, i, j - 1) ? 1 : 0;
count += ok(board, i, j + 1) ? 1 : 0;
count += ok(board, i + 1, j - 1) ? 1 : 0;
count += ok(board, i + 1, j) ? 1 : 0;
count += ok(board, i + 1, j + 1) ? 1 : 0;
return count;
}
bool ok(vector<vector<int>> &board, int i, int j) { return i >= 0 && i < board.size() && j >= 0 && j < board[0].size() && (board[i][j] & 1) == 1; }
void set(vector<vector<int>> &board, int i, int j) { board[i][j] |= 2; }
int get(vector<vector<int>> &board, int i, int j) { return board[i][j] >> 1; }
};
void testGameOfLife()
{
Solution s;
vector<vector<int>> n1 = {{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}};
vector<vector<int>> n2 = {{1, 1}, {1, 0}};
vector<vector<int>> o1 = {{0, 0, 0}, {1, 0, 1}, {0, 1, 1}, {0, 1, 0}};
vector<vector<int>> o2 = {{1, 1}, {1, 1}};
s.gameOfLife(n1);
s.gameOfLife(n2);
EXPECT_TRUE(o1 == n1);
EXPECT_TRUE(o2 == n2);
EXPECT_SUMMARY;
}
int main()
{
testGameOfLife();
return 0;
}