forked from udit034/LeetCode_Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.Game of Life.java
43 lines (40 loc) · 1.5 KB
/
Solution.Game of Life.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
public class Solution {
public boolean isValid( int i, int j,int m,int n, int[][] board )
{
return ( i >= 0 && i < m ) && ( j >= 0 && j < n ) && ( board[i][j] == 1 );
}
public void gameOfLife(int[][] board) {
int m = board.length;
int n = board[0].length;
int[][] b = new int[ board.length ][ board[0].length ];
for( int i = 0; i < m; i++ )
{
for( int j = 0; j < n; j++ )
{
int l = 0;
if( isValid( i-1, j-1, m, n, board ) ) l++;
if( isValid( i-1, j, m, n, board ) ) l++;
if( isValid( i-1, j+1, m, n, board ) ) l++;
if( isValid( i, j-1, m, n, board ) ) l++;
if( isValid( i, j+1, m, n, board ) ) l++;
if( isValid( i+1, j-1, m, n, board ) ) l++;
if( isValid( i+1, j, m, n, board ) ) l++;
if( isValid( i+1, j+1, m, n, board ) ) l++;
if( board[i][j] == 1 )
{
if( l < 2 )
b[i][j] = 0;
else if( l == 2 || l == 3 )
b[i][j] = 1;
else if( l > 3 )
b[i][j] = 0;
}
else if( board[i][j] == 0 && l == 3 )
b[i][j] = 1;
}
}
for( int i = 0; i < m; i++ )
for( int j = 0; j < n; j++ )
board[i][j] = b[i][j];
}
}