There is no commentSelect some text and then click Comment, or simply add a comment to this page from below to start a discussion.
289. Game of Life
Idea
題目要求將生存遊戲 boards 的格點置換為下一個狀態 先不考慮空間複雜度 最直覺的解法是
創建一個儲存下一個狀態的二維陣列 results
遍歷每個格點把下一個狀態存取到 results (要小心處理訪問陣列的上下界)
再遍歷一次將 boards 的格點取代為 results 的格點
時間複雜度為 O( m _ n ) 空間複雜度為 O( m _ n )
functiongameOfLife(board){const m = board.length,
n = board[0].length,
results = Array.from(Array(m),(_)=>Array(n))for(let i =0; i < m; i++){for(let j =0; j < n; j++){
results[i][j]=setStatus(board, i, j, m, n)}}for(let i =0; i < m; i++){for(let j =0; j < n; j++){
board[i][j]= results[i][j]}}}functionsetStatus(board, x, y, m, n){let liveCount =0for(let i = Math.max(0, x -1); i <= Math.min(m -1, x +1); i++){for(let j = Math.max(0, y -1); j <= Math.min(n -1, y +1); j++){if(i !== x || j !== y) liveCount += board[i][j]===1}}returnNumber(
board[x][y]===1? liveCount >=2&& liveCount <=3: liveCount ===3)}
functiongameOfLife(board){/*
status of board definition:
0 = dead before, dead after.
1 = alive before, alive after.
2 = alive before, dead after.
3 = dead before, alive after.
*/const m = board.length,
n = board[0].length
for(let i =0; i < m; i++){for(let j =0; j < n; j++){
board[i][j]=setStatus(board, i, j, m, n)}}for(let i =0; i < m; i++){for(let j =0; j < n; j++){
board[i][j]%=2}}}functionsetStatus(board, x, y, m, n){let liveCount =0for(let i = Math.max(0, x -1); i <= Math.min(m -1, x +1); i++){for(let j = Math.max(0, y -1); j <= Math.min(n -1, y +1); j++){if(i !== x || j !== y){if(board[i][j]===2) liveCount +=1elseif(board[i][j]===3) liveCount +=0else liveCount += board[i][j]}}}if(board[x][y]===1&&(liveCount <2|| liveCount >3))return2elseif(board[x][y]===0&& liveCount ===3)return3elsereturn board[x][y]}