Skip to content

Commit d15d88a

Browse files
committed
[leet] game of life-re (mid)
1 parent b34bf65 commit d15d88a

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

허현빈/8주차/Game of Life.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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 newBoard = Array.from({ length: board.length }, () =>
7+
Array.from({ length: board[0].length }).fill(0)
8+
);
9+
const dir = [
10+
[1, 0],
11+
[-1, 0],
12+
[0, 1],
13+
[0, -1],
14+
[-1, -1],
15+
[1, 1],
16+
[1, -1],
17+
[-1, 1],
18+
];
19+
20+
for (let i = 0; i < board.length; i++) {
21+
for (let j = 0; j < board[0].length; j++) {
22+
let zeroCount = 0;
23+
for (let k = 0; k < dir.length; k++) {
24+
const ny = i + dir[k][0];
25+
const nx = j + dir[k][1];
26+
if (ny >= 0 && ny < board.length && nx >= 0 && nx < board[0].length) {
27+
if (board[ny][nx] === 1) {
28+
zeroCount++;
29+
}
30+
}
31+
}
32+
if (board[i][j] === 1 && zeroCount <= 1) {
33+
newBoard[i][j] = 0;
34+
} else if (board[i][j] === 1 && (zeroCount === 2 || zeroCount === 3)) {
35+
newBoard[i][j] = 1;
36+
} else if (board[i][j] === 1 && zeroCount > 3) {
37+
newBoard[i][j] = 0;
38+
} else if (board[i][j] === 0 && zeroCount === 3) {
39+
newBoard[i][j] = 1;
40+
}
41+
}
42+
}
43+
for (let i = 0; i < board.length; i++) {
44+
for (let j = 0; j < board[0].length; j++) {
45+
board[i][j] = newBoard[i][j];
46+
}
47+
}
48+
};

0 commit comments

Comments
 (0)