forked from javadev/LeetCode-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
37 lines (34 loc) · 1.17 KB
/
Solution.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
package g0201_0300.s0289_game_of_life;
// #Medium #Array #Matrix #Simulation #Top_Interview_150_Matrix
// #2025_03_09_Time_0_ms_(100.00%)_Space_41.90_MB_(24.53%)
public class Solution {
public void gameOfLife(int[][] board) {
int m = board.length;
int n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int lives = lives(board, i, j, m, n);
if (board[i][j] == 0 && lives == 3) {
board[i][j] = 2;
} else if (board[i][j] == 1 && (lives == 2 || lives == 3)) {
board[i][j] = 3;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
board[i][j] >>= 1;
}
}
}
private int lives(int[][] board, int i, int j, int m, int n) {
int lives = 0;
for (int r = Math.max(0, i - 1); r <= Math.min(m - 1, i + 1); r++) {
for (int c = Math.max(0, j - 1); c <= Math.min(n - 1, j + 1); c++) {
lives += board[r][c] & 1;
}
}
lives -= board[i][j] & 1;
return lives;
}
}