-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameOfLife.java
More file actions
49 lines (44 loc) · 1.25 KB
/
GameOfLife.java
File metadata and controls
49 lines (44 loc) · 1.25 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
// 289. Game of Life
// https://leetcode.com/problems/game-of-life/
class Solution {
public void gameOfLife(int[][] board) {
int col=board.length;
int row=board[0].length;
int arr[][]=new int[col][row];
for(int i=0;i<col;i++)
{
for(int j=0;j<row;j++)
{
int count=neighborsCount(board,i,j);
if(board[i][j]==0 && count==3)
arr[i][j]=1;
else if(board[i][j]==1 && (count==2 ||count==3))
arr[i][j]=1;
}
}
for(int i=0;i<col;i++)
{
for(int j=0;j<row;j++)
{
board[i][j]=arr[i][j];
}
}
}
static int neighborsCount(int [][]arr,int i,int j)
{
int count=0;
int n[][]={
{-1,-1},{-1,0},{-1,1},
{0,-1},{0,1},
{1,-1},{1,0},{1,1}
};
for(int dia[]:n)
{
int x=dia[0]+i;
int y=dia[1]+j;
if(x>=0 && y>=0 && x<arr.length && y<arr[0].length && arr[x][y]==1)
count++;
}
return count;
}
}