-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGameOfLife.java
71 lines (66 loc) · 2.33 KB
/
GameOfLife.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
/**
* Runtime: 1 ms, faster than 20.83% of Java online submissions for Game of Life.
* Memory Usage: 38.4 MB, less than 7.69% of Java online submissions for Game of Life.
*/
class Solution {
int[] X_DIR = new int[] { 0, 0, 1, 1, 1, -1, -1, -1 };
int[] Y_DIR = new int[] { -1, 1, 1, -1, 0, 1, -1, 0 };
public void gameOfLife(int[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) {
return;
}
ZeroOne[][] zeroOnes = new ZeroOne[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
zeroOnes[i][j] = new ZeroOne();
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
calculateCount(board, zeroOnes, i, j);
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == 0 && zeroOnes[i][j].ones == 3) {
board[i][j] = 1;
} else if (board[i][j] == 1 && zeroOnes[i][j].ones < 2) {
board[i][j] = 0;
} else if (board[i][j] == 1 && zeroOnes[i][j].ones > 3) {
board[i][j] = 0;
} else if (board[i][j] == 1 && (zeroOnes[i][j].ones == 2 || zeroOnes[i][j].ones == 3)) {
board[i][j] = 1;
} else {
board[i][j] = 0;
}
}
}
}
private void calculateCount(int[][] board, ZeroOne[][] zeroOnes, int x, int y) {
for (int i = 0; i < 8; i++) {
int newX = x + X_DIR[i];
int newY = y + Y_DIR[i];
if (insideBounds(newX, newY, board.length, board[0].length)) {
if (board[newX][newY] == 0) {
zeroOnes[x][y].zeros++;
} else {
zeroOnes[x][y].ones++;
}
}
}
}
private boolean insideBounds(int x, int y, int X, int Y) {
if (x < 0 || x >= X || y < 0 || y >= Y) {
return false;
}
return true;
}
class ZeroOne {
int zeros;
int ones;
public ZeroOne() {
zeros = 0;
ones = 0;
}
}
}