forked from super30admin/Array-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame of Life.java
99 lines (89 loc) · 2.62 KB
/
Game of Life.java
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
94
95
96
97
98
99
// Time Complexity : O(m*n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
class Solution {
public void gameOfLife(int[][] board) {
int r = board.length;
int c = board[0].length;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
int temp = sol(board,i,j);
board[i][j] = temp;
}
}
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(board[i][j]==2){
board[i][j]=1;
}
if(board[i][j]==-2){
board[i][j]=0;
}
}
}
}
public int sol(int[][]board,int r,int c){
int live = 0;
//up
if(r-1>=0){
if(board[r-1][c]==1 || board[r-1][c]==-2 ){
live++;
}
}
//down
if(r+1<board.length){
if(board[r+1][c]==1 || board[r+1][c]==-2 ){
live++;
}
}
//left
if(c-1>=0){
if(board[r][c-1]==1 || board[r][c-1]==-2 ){
live++;
}
}
//right
if(c+1<board[0].length){
if(board[r][c+1]==1 || board[r][c+1]==-2 ){
live++;
}
}
//upper left diagonal
if(r-1>=0 && c-1>=0){
if(board[r-1][c-1]==1 || board[r-1][c-1]==-2 ){
live++;
}
}
//uper right diagonal
if(r-1>=0 && c+1<board[0].length){
if(board[r-1][c+1]==1 || board[r-1][c+1]==-2 ){
live++;
}
}
// lower left diagonal
if(r+1<board.length && c-1>=0){
if(board[r+1][c-1]==1 || board[r+1][c-1]==-2 ){
live++;
}
}
// lower right diagonal
if(r+1<board.length && c+1<board[0].length){
if(board[r+1][c+1]==1 || board[r][c+1]==-2 ){
live++;
}
}
if( board[r][c]==0 && live==3){
return 2;
}
else if(board[r][c]== 1 && live<2){
return -2;
}
else if(board[r][c]==1 && live>3){
return -2;
}
else if((board[r][c]==1 && (live==2 || live==3))){
return 1;
}
return board[r][c];
}
}