forked from super30admin/Array-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem3.java
88 lines (85 loc) · 2.42 KB
/
Problem3.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class Solution {
public void gameOfLife(int[][] board) {
// if originially dead, now live ==> 2
// if originally live, now dead ==> -1
int m = board.length;
int n = board[0].length;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
int liveCount = liveCount(board, i, j);
// rule 1 and rule 3
if(board[i][j] == 1 && (liveCount < 2 || liveCount > 3 )){
board[i][j] = -1;
}
// rule 4
if(board[i][j] == 0 && liveCount == 3){
board[i][j] = 2;
}
}
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(board[i][j] == -1){
board[i][j] = 0;
}
if(board[i][j] == 2){
board[i][j] = 1;
}
}
}
}
public int liveCount(int[][] board, int i, int j){
int m = board.length;
int n = board[0].length;
int result = 0;
//top
if(i > 0){
if(board[i-1][j] == 1 || board[i-1][j] == -1){
result++;
}
}
// left
if(j > 0){
if(board[i][j-1] == 1 || board[i][j-1] == -1){
result++;
}
}
// right
if(j < n-1){
if(board[i][j+1] == 1 || board[i][j+1] == -1){
result++;
}
}
// bottom
if(i < m-1){
if(board[i+1][j] == 1 || board[i+1][j] == -1){
result++;
}
}
// diagonal up left
if( i > 0 && j > 0){
if(board[i-1][j-1] == 1 || board[i-1][j-1] == -1){
result++;
}
}
// diagonal up right
if( i > 0 && j < n-1){
if(board[i-1][j+1] == 1 || board[i-1][j+1] == -1){
result++;
}
}
// diagonal down left
if( i < m-1 && j > 0){
if(board[i+1][j-1] == 1 || board[i+1][j-1] == -1){
result++;
}
}
// diagonal down right
if( i < m-1 && j < n-1){
if(board[i+1][j+1] == 1 || board[i+1][j+1] == -1){
result++;
}
}
return result;
}
}