Skip to content

Commit cb88dd5

Browse files
committed
Create 289.生命游戏.js
1 parent 39aeffe commit cb88dd5

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

289.生命游戏.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @param {number[][]} board
3+
* @return {void} Do not return anything, modify board in-place instead.
4+
*/
5+
var gameOfLife = function(board) {
6+
const d = [[-1, -1], [-1, 0], [-1, 1], [0, 1], [1, 1], [1, 0], [1, -1], [0, -1]];
7+
for (let i = 0; i< board.length; i++) {
8+
for (let j = 0; j < board[i].length; j++) {
9+
let alive = 0;
10+
for (const t of d) {
11+
if (board[i + t[0]] && (board[i + t[0]][j + t[1]] & 1) === 1) {
12+
alive++;
13+
}
14+
}
15+
if (board[i][j] === 0) {
16+
if (alive === 3) {
17+
board[i][j] = 2;
18+
}
19+
} else {
20+
if (alive < 2 || alive > 3) {
21+
board[i][j] = 3;
22+
}
23+
}
24+
}
25+
}
26+
for (let i = 0; i< board.length; i++) {
27+
for (let j = 0; j < board[i].length; j++) {
28+
if (board[i][j] > 1) {
29+
board[i][j] = 3 - board[i][j];
30+
}
31+
}
32+
}
33+
return board;
34+
};

0 commit comments

Comments
 (0)