-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgameOfLife.java
More file actions
65 lines (49 loc) · 1.95 KB
/
gameOfLife.java
File metadata and controls
65 lines (49 loc) · 1.95 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Solution {
public void gameOfLife(int[][] board) {
int[][] res = new int[board.length][ board[0].length];
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[0].length;j++)
{
res[i][j] = checkStatus(board,i ,j);
}
for(int i = 0; i < board.length; i++)
for(int j = 0; j < board[0].length;j++)
{
board[i][j] = res[i][j] ;
}
return;
}
public int checkStatus(int[][] board, int i , int j)
{
int sum = getNeighbors(0,board, i , j);
if(sum<2 && board[i][j]==1)
return 0;
if((sum==2||sum==3)&&board[i][j]==1)
return 1;
if((sum >3)&&board[i][j]==1)
return 0;
if((sum==3)&&board[i][j]==0)
return 1;
return 0;
}
public int getNeighbors(int sum,int[][] board, int i , int j )
{
sum = 0;
System.out.println("i:"+i+" j:"+j);
if(i-1<0 && (j-1>0 && i<board.length-1 && j<board[0].length-1))
{
sum = board[i+1][j]+
board[i+1][j-1]+
board[i][j-1]+
board[i+1][j+1]+
board[i][j+1];
}
if(j-1<0 && (i-1>0 && i<board.length-1 && j<board[0].length-1))
sum = board[i+1][j]+board[i+1][j+1]+board[i][j+1]+board[i-1][j]+board[i-1][j+1];
if( j>board[0].length &&!(j-1<0 || i>board.length||i-1<0))
sum = board[i+1][j]+board[i+1][j-1]+board[i][j-1] +board[i-1][j]+board[i-1][j-1];
if(i>board.length &&!(j-1<0 || i-1<0 || j>board[0].length))
sum = board[i][j-1]+board[i][j+1] +board[i-1][j]+board[i-1][j-1]+board[i-1][j+1] ;
return sum;
}
}