250x250
반응형
Notice
Recent Posts
Recent Comments
Link
N
(Leet Code JS)Game of Life 본문
728x90
반응형
https://leetcode.com/problems/game-of-life/
Conway game의 룰을 따른 시뮬레이션
현재의 셀의 상태와 주변 8방향의 셀 상태를 파악해 Next state를 구하는 문제.
룰을 잘 읽으면 쉽게 구현할 수 있는 문제다.
const gameOfLife = (board) => {
const m = board.length;
const n = board[0].length;
const directX = [-1, 1, 0, 0, -1, -1, 1, 1];
const directY = [0, 0, -1, 1, -1, 1, -1, 1];
const nextBoard = Array.from({length: m}, () => Array(n).fill(0));
const checkRange = (x, y) => {
if(x >= 0 && x < m && y >= 0 && y < n){
return true;
}
return false;
}
for(let i = 0; i < m; i++){
for(let j = 0; j < n; j++){
const current = board[i][j];
let liveCell = 0;
let deadCell = 0;
for(let k = 0; k < 8; k++){
const nx = i + directX[k];
const ny = j + directY[k];
if(checkRange(nx, ny)){
if(board[nx][ny]){
liveCell++;
} else{
deadCell++;
}
}
}
if(current){
if(liveCell >= 2 && liveCell <= 3){
nextBoard[i][j] = 1;
}
} else{
if(liveCell === 3){
nextBoard[i][j] = 1;
}
}
}
}
for(let i = 0; i < m; i++){
for(let j = 0; j < n; j++){
board[i][j] = nextBoard[i][j];
}
}
};
728x90
반응형
'Leet Code 알고리즘' 카테고리의 다른 글
(Leet Code JS)Longest Increasing Subsequence (0) | 2022.08.20 |
---|---|
(Leet Code JS)Diagonal Traverse (0) | 2022.07.30 |
(Leet Code JS)Candy (0) | 2022.07.10 |
(Leet Code JS)Wiggle Subsequence (0) | 2022.07.09 |
(Leet Code JS)Maximum Units on a Truck (0) | 2022.07.09 |