Skip to content

Commit 852a6f5

Browse files
committed
feat: solved 289
1 parent 9cf5f5c commit 852a6f5

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.fghpdf.GameOfLife;
2+
3+
/**
4+
* @author fghpdf
5+
* @date 2019/12/25
6+
* https://leetcode.com/problems/game-of-life/
7+
* https://leetcode.com/problems/game-of-life/discuss/73223/Easiest-JAVA-solution-with-explanation
8+
* 没懂
9+
**/
10+
public class Solution {
11+
public void gameOfLife(int[][] board) {
12+
if (board == null || board.length == 0) {
13+
return;
14+
}
15+
int m = board.length, n = board[0].length;
16+
17+
for (int i = 0; i < m; i++) {
18+
for (int j = 0; j < n; j++) {
19+
int lives = liveNeighbors(board, m, n, i, j);
20+
21+
// In the beginning, every 2nd bit is 0;
22+
// So we only need to care about when will the 2nd bit become 1.
23+
if (board[i][j] == 1 && lives >= 2 && lives <= 3) {
24+
board[i][j] = 3; // Make the 2nd bit 1: 01 ---> 11
25+
}
26+
if (board[i][j] == 0 && lives == 3) {
27+
board[i][j] = 2; // Make the 2nd bit 1: 00 ---> 10
28+
}
29+
}
30+
}
31+
32+
for (int i = 0; i < m; i++) {
33+
for (int j = 0; j < n; j++) {
34+
board[i][j] >>= 1; // Get the 2nd state.
35+
}
36+
}
37+
}
38+
39+
public int liveNeighbors(int[][] board, int m, int n, int i, int j) {
40+
int lives = 0;
41+
for (int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) {
42+
for (int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) {
43+
lives += board[x][y] & 1;
44+
}
45+
}
46+
lives -= board[i][j] & 1;
47+
return lives;
48+
}
49+
}

0 commit comments

Comments
 (0)