forked from super30admin/Array-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameofLife.java
45 lines (34 loc) · 1.18 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
// Time Complexity :
// Space Complexity :
// Did this code successfully run on Leetcode :
// Any problem you faced while coding this :
// Your code here along with comments explaining your approach
class Solution {
int[][] dir={{1,-1},{1,0},{1,1},{0,-1},{0,1},{-1,-1},{-1,0},{-1,1}};
public void gameOfLife(int[][] board) {
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
int live=0;
for(int[] d:dir){
if((i+d[0])<0||(i+d[0])>=board.length||(j+d[1])<0||(j+d[1])>=board[0].length){
continue;
}
if(board[i+d[0]][j+d[1]]==1||board[i+d[0]][j+d[1]]==2){
live++;
}
}
if(board[i][j]==1&&(live<2||live>3)){
board[i][j]=2;
}
if(board[i][j]==0&&live==3){
board[i][j]=3;
}
}
}
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
board[i][j]=board[i][j]%2;
}
}
}
}