-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_289_ConwayGameOfLife.cpp
93 lines (75 loc) · 2.53 KB
/
LC_289_ConwayGameOfLife.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
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
https://leetcode.com/problems/game-of-life/
289. Game of Life
https://binarysearch.com/problems/Conway's-Game-of-Life/solutions
*/
class Solution {
public:
void gameOfLife_ExtraSpace(vector<vector<int>>& board) {
int m = board.size();
int n = board[0].size();
int dirs[8][2] = {
{-1,-1}, {-1,0}, {-1,+1}, {0,+1}, {+1,+1}, {+1,0}, {+1,-1}, {0,-1}
};
vector<vector<int>> ans(m, vector<int>(n,0));
int liveCount = 0, x=0, y=0;
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
liveCount=0;
for(auto d: dirs)
{
x=i+d[0];
y=j+d[1];
if(x<0 || y<0 || x>=m || y>=n || board[x][y]==0)
continue;
else
liveCount++;
}
if((board[i][j] && (liveCount==2 || liveCount==3)) || (!board[i][j]) && liveCount ==3)
ans[i][j]=1;
else
ans[i][j]=0;
}
}
board = ans;
}//end
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
int n = board[0].size();
int dirs[8][2] = {
{-1,-1}, {-1,0}, {-1,+1}, {0,+1}, {+1,+1}, {+1,0}, {+1,-1}, {0,-1}
};
int x=0, y=0;
int diff = 0;
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(board[i][j]>0) //if it is a live cell
diff = +1;
else
diff = -1;
for(auto d: dirs) // for each cell. look into its 8 neighbours
{
x = i+d[0]; y = j+d[1];
if(x<0 || y<0 || x>=m || y>=n)
continue;
else if(board[x][y]>0) // if it is neighbours are live
board[i][j] += diff;
}
}
}
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if((board[i][j] >= 3 && board[i][j] <= 4) || board[i][j] == -3) // 1 + 2 or 3 live neighbours // 0 + -3
board[i][j] = 1;
else
board[i][j] = 0;
}
}
}//end
};