-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path289. Game of Life
55 lines (45 loc) · 1.76 KB
/
289. Game of Life
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
class Solution {
public void gameOfLife(int[][] board) {
if (board == null || board.length == 0) return;
int m = board.length, n = board[0].length;
// Iterate through each cell
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int liveNeighbors = countLiveNeighbors(board, i, j);
// Rule 1 or Rule 3
if (board[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {
board[i][j] = -1; // -1 signifies the cell is currently live but will die
}
// Rule 4
if (board[i][j] == 0 && liveNeighbors == 3) {
board[i][j] = 2; // 2 signifies the cell is currently dead but will live
}
}
}
// Update the board to the next state
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] > 0) {
board[i][j] = 1;
} else {
board[i][j] = 0;
}
}
}
}
private int countLiveNeighbors(int[][] board, int row, int col) {
int m = board.length, n = board[0].length;
int count = 0;
// Iterate over all 8 neighbors
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) continue; // Skip the cell itself
int r = row + i, c = col + j;
if (r >= 0 && r < m && c >= 0 && c < n && Math.abs(board[r][c]) == 1) {
count++;
}
}
}
return count;
}
}