Skip to content

Commit e137a49

Browse files
committed
Time: 1 ms (65.17%), Space: 55.9 MB (5.67%) - LeetHub
1 parent 1e5bef4 commit e137a49

File tree

1 file changed

+35
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)