Game of Life LeetCode solution in Java

1
class Solution {
2
public void gameOfLife(int[][] board) {
3
int m = board.length, n = board[0].length;
4
int[][] next = new int[m][n];
5
for (int i = 0; i < m; i++) {
6
for (int j = 0; j < n; j++) {
7
next[i][j] = nextState(board, i, j, m, n);
8
}
9
}
10
for (int i = 0; i < m; i++) {
11
for (int j = 0; j < n; j++) {
12
board[i][j] = next[i][j];
13
}
14
}
15
}
16

17
public int nextState(int[][] board, int i, int j, int m, int n) {
18
int ones = 0;
19
for (int x = -1; x <= 1; x++) {
20
for (int y = -1; y <= 1; y++) {
21
if (x == 0 && y == 0) {
22
continue;
23
}
24
int a = i + x, b = j + y;
25
if (a >= 0 && a < m) {
26
if (b >= 0 && b < n) {
27
ones += board[a][b];
28
}
29
}
30
}
31
}
32
if (board[i][j] == 0) {
33
return ones == 3 ? 1 : 0;
34
} else {
35
if (ones == 2 || ones == 3) {
36
return 1;
37
} else {
38
return 0;
39
}
40
}
41
}
42
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0