Game of Life LeetCode solution in JavaScript

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 m = board.length,
7
n = board[0].length;
8
let copy = JSON.parse(JSON.stringify(board));
9

10
const getNeighbor = (row, col) => {
11
let radius = [-1, 0, 1],
12
count = 0;
13
for (let i = 0; i < 3; i++) {
14
for (let j = 0; j < 3; j++) {
15
if (
16
!(radius[i] == 0 && radius[j] == 0) &&
17
copy[row + radius[i]] &&
18
copy[row + radius[i]][col + radius[j]]
19
) {
20
let neighbor = copy[row + radius[i]][col + radius[j]];
21
if (neighbor == 1) {
22
count++;
23
}
24
}
25
}
26
}
27
return count;
28
};
29

30
for (let i = 0; i < m; i++) {
31
for (let j = 0; j < n; j++) {
32
const count = getNeighbor(i, j);
33
if (copy[i][j] == 1) {
34
if (count < 2 || count > 3) {
35
board[i][j] = 0;
36
}
37
} else {
38
if (count == 3) {
39
board[i][j] = 1;
40
}
41
}
42
}
43
}
44
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0