-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame_of_life.cpp
More file actions
53 lines (42 loc) · 1.38 KB
/
game_of_life.cpp
File metadata and controls
53 lines (42 loc) · 1.38 KB
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
class Solution {
public:
int check(int r, int c, vector<vector<int>>& board){
int cnt = 0;
if(r > 0)
cnt += (board[r - 1][c] & 1);
if(r + 1 < board.size())
cnt += (board[r + 1][c] & 1);
if(c > 0)
cnt += (board[r][c - 1] & 1);
if(c + 1 < board[r].size())
cnt += (board[r][c + 1] & 1);
if(r > 0 && c > 0)
cnt += (board[r - 1][c - 1] & 1);
if(r > 0 && c + 1 < board[r].size())
cnt += (board[r - 1][c + 1] & 1);
if(r + 1 < board.size() && c > 0)
cnt += (board[r + 1][c - 1] & 1);
if(r + 1 < board.size() && c + 1 < board[r].size())
cnt += (board[r + 1][c + 1] & 1);
return cnt;
}
void gameOfLife(vector<vector<int>>& board) {
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[i].size(); j++){
int cnt = check(i, j, board);
if((board[i][j] & 1) == 1){
if(cnt == 2 || cnt == 3)
board[i][j] = 3;
}else{
if(cnt == 3)
board[i][j] = 2;
}
}
}
for(int i = 0; i < board.size(); i++){
for(int j = 0; j < board[i].size(); j++){
board[i][j] >>= 1;
}
}
}
};