-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame of Life.java
More file actions
52 lines (43 loc) · 1.23 KB
/
Copy pathGame of Life.java
File metadata and controls
52 lines (43 loc) · 1.23 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
class Solution {
public void gameOfLife(int[][] board) {
if(board==null || board.length==0||board[0].length==0)
return;
int m=board.length;
int n=board[0].length;
int[] x = {-1, -1, 0, 1, 1, 1, 0, -1};
int[] y = {0, 1, 1, 1, 0, -1, -1, -1};
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int count=0;
for(int k=0; k<8; k++){
int nx=i+x[k];
int ny=j+y[k];
if(nx>=0&&nx<m&&ny>=0&&ny<n&&(board[nx][ny]&1)==1){
count++;
}
}
//<2 die
if(count<2){
board[i][j] &= 1;
}
//same state
if(count==2||count==3){
board[i][j] |= board[i][j]<<1;
}
//go live
if(count==3){
board[i][j] |=2;
}
//>3 die
if(count>3){
board[i][j] &=1;
}
}
}
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
board[i][j] = board[i][j]>>1;
}
}
}
}