forked from super30admin/Array-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameOfLife289
47 lines (44 loc) · 1.45 KB
/
gameOfLife289
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
class Solution {
//289. Game of Life
//Time complexity: O(rows*columns)
//Space complexity: O(1)
int rows;
int cols;
public void gameOfLife(int[][] board) {
rows = board.length;
cols = board[0].length;
for(int i = 0;i < rows;i++){
for(int j =0; j < cols;j++){
int count = liveCount(board,i,j);
//making live cell dead
//1---> 0 (3)
if(board[i][j] ==1 && (count < 2 || count>3))
board[i][j] = 3;
//making a dead cell --live
//0--->1 (2)
else if(board[i][j]== 0 && count==3)
board[i][j]=2;
}
}
for(int i = 0;i < rows;i++){
for(int j =0; j < cols;j++){
if(board[i][j]==3)
board[i][j]=0;
else if(board[i][j]==2)
board[i][j]=1;
}
}
}
private int liveCount(int[][] board,int i,int j){
int count=0;
int[][] dirs = {{0,-1},{0,1},{-1,0},{1,0},{-1,1},{-1,-1},{1,-1},{1,1}};
for(int[] dir :dirs){
int row = dir[0]+i;
int col = dir[1]+j;
if(row>=0 && col>=0 && row < rows && col < cols && (board[row][col]==1 || board[row][col]==3)){
count++;
}
}
return count;
}
}