-
Notifications
You must be signed in to change notification settings - Fork 278
/
Copy pathGameofLife.java
79 lines (77 loc) · 2.67 KB
/
GameofLife.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
// Author: Shobhit Behl (LC: shobhitbruh)
class Solution {
public void gameOfLife(int[][] board) {
int[][] ans=new int[board.length][board[0].length];
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
int n=0;
if(board[i][j]==1){
if(i-1>=0&&board[i-1][j]==1){
n++;
}
if(i+1<board.length&&board[i+1][j]==1){
n++;
}
if(j-1>=0&&board[i][j-1]==1){
n++;
}
if(j+1<board[0].length&&board[i][j+1]==1){
n++;
}
if(i-1>=0&&j-1>=0&&board[i-1][j-1]==1){
n++;
}
if(i+1<board.length&&j-1>=0&&board[i+1][j-1]==1){
n++;
}
if(i-1>=0&&j+1<board[0].length&&board[i-1][j+1]==1){
n++;
}
if(i+1<board.length&&j+1<board[0].length&&board[i+1][j+1]==1){
n++;
}
if(n<2||n>3){
ans[i][j]=0;
}else{
ans[i][j]=board[i][j];
}
}else{
if(i-1>=0&&board[i-1][j]==1){
n++;
}
if(i+1<board.length&&board[i+1][j]==1){
n++;
}
if(j-1>=0&&board[i][j-1]==1){
n++;
}
if(j+1<board[0].length&&board[i][j+1]==1){
n++;
}
if(i-1>=0&&j-1>=0&&board[i-1][j-1]==1){
n++;
}
if(i+1<board.length&&j-1>=0&&board[i+1][j-1]==1){
n++;
}
if(i-1>=0&&j+1<board[0].length&&board[i-1][j+1]==1){
n++;
}
if(i+1<board.length&&j+1<board[0].length&&board[i+1][j+1]==1){
n++;
}
if(n==3){
ans[i][j]=1;
}else{
ans[i][j]=board[i][j];
}
}
}
}
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
board[i][j]=ans[i][j];
}
}
}
}