엔지니어 게시판
LeetCode 솔루션 분류

289. Game of Life

컨텐츠 정보

본문

[ LeetCode 시즌 3 ] 2022년 4월 11일 문제입니다.

Medium 289. Game of Life

According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population.
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.

 

Example 1:

Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]

Example 2:

Input: board = [[1,1],[1,0]]
Output: [[1,1],[1,1]]

 

Constraints:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 25
  • board[i][j] is 0 or 1.

 

Follow up:

  • Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
  • In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?


관련자료

댓글 6

CANUS님의 댓글

  • 익명
  • 작성일
Runtime: 0 ms, faster than 100.00% of Swift online submissions for Game of Life.
Memory Usage: 14.3 MB, less than 12.12% of Swift online submissions for Game of Life.

class Solution {
    func gameOfLife(_ board: inout [[Int]]) {
        guard board.count >= 1 else { return }
        guard board[0].count <= 25 else { return }
        
        let orgBoard = board
        
        func numOfNeighborsInRow(_ y: Int, _ x: Int, hasCurrentCell: Bool = false) -> Int {
            var neighbors = 0
            
            if x >= 1 {
                neighbors += (orgBoard[y][x-1] == 1 ? 1 : 0)
            }
            
            if !currentCell {
                neighbors += (orgBoard[y][x] == 1 ? 1 : 0)
            }
            
            if x+1 < orgBoard[y].count {
                neighbors += (orgBoard[y][x+1] == 1 ? 1 : 0)
            }
            
            return neighbors
        }
        
        for y in 0..<orgBoard.count {
            for x in 0..<orgBoard[y].count {                
                let isCellLive: Bool = orgBoard[y][x] == 1
                
                var liveNeighbors: Int = 0
                
                if y-1 >= 0 { 
                    liveNeighbors += numOfNeighborsInRow(y-1, x)
                }
                
                if y >= 0 {                   
                    liveNeighbors += numOfNeighborsInRow(y, x, hasCurrentCell: true)
                }
                
                if y+1 < orgBoard.count {                   
                    liveNeighbors += numOfNeighborsInRow(y+1, x)
                }

                if isCellLive {
                    if liveNeighbors < 2 {
                        // live 
                        board[y][x] = 0
                    } else if liveNeighbors == 2 || liveNeighbors == 3 {
                        // next generation
                        board[y][x] = 1
                    } else if liveNeighbors > 3 {
                        // die
                        board[y][x] = 0
                    }             
                } else {
                    if liveNeighbors == 3 {
                        // live
                        board[y][x] = 1
                    }
                }
            }
        }
    }
}

austin님의 댓글

  • 익명
  • 작성일
A C++ constant O(1) space complexity solution
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Game of Life.
Memory Usage: 6.8 MB, less than 84.44% of C++ online submissions for Game of Life.
class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        auto check = [&](int y, int x) {
            return (y < 0 || y == board.size() || x < 0 || x == board[0].size()) ? 0 : board[y][x]&1;
        };
        const pair<int, int> dir[] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
        for(int y = 0; y < board.size(); ++y) for(int x = 0; x < board[0].size(); ++x) {
            int alive = 0;
            for(auto [ny,nx] : dir) alive += check(y + ny, x + nx);
            board[y][x] |= board[y][x] ? ((alive & 6) == 2 ? 2 : 0) : (alive == 3 ? 2 : 0);
        }
        for(auto &row : board) for(auto &cell : row) cell >>= 1;
    }
};

mingki님의 댓글

  • 익명
  • 작성일
C++
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Game of Life.
Memory Usage: 7.1 MB, less than 20.27% of C++ online submissions for Game of Life.
class Solution { 
public:
    void gameOfLife(vector<vector<int>>& board) {
        stack<pair<int, int>> change;
        
        
        for (int i = 0; i < board.size(); ++i) {
            for (int j = 0; j < board[i].size(); ++j) {
                int count = 0;
                
                count += i > 0 && j > 0 ? board[i - 1][j - 1] : 0;
                count += i > 0 ? board[i - 1][j] : 0;
                count += i > 0 && j < board[i - 1].size() - 1 ? board[i - 1][j + 1] : 0;
                count += j > 0 ? board[i][j - 1] : 0;
                count += j < board[i].size() - 1 ? board[i][j + 1] : 0;
                count += i < board.size() - 1 && j > 0 ? board[i + 1][j - 1] : 0;
                count += i < board.size() - 1 ? board[i + 1][j] : 0;
                count += i < board.size() - 1 && j < board[i + 1].size() - 1 ? board[i + 1][j + 1] : 0;
                
                if ((board[i][j] && (count < 2 || count > 3)) ||
                    (!board[i][j] && count == 3)) {
                    change.push(pair<int, int>(i, j));
                }
            }
        }
        while (!change.empty()) {
            pair<int, int> p = change.top(); change.pop();
            board[p.first][p.second] ^= 1;
        }
    }
};

bobkim님의 댓글

  • 익명
  • 작성일
class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m=board.size();
        int n=board[0].size();
        int sum=0;
        
        vector<vector<int>> Tmpboard(m+2,vector<int>(n+2,0));
        
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                Tmpboard[i+1][j+1] = board[i][j];  
            };
        };
        
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                sum=Tmpboard[i][j]+Tmpboard[i][j+1]+Tmpboard[i][j+2]+Tmpboard[i+1][j]+Tmpboard[i+1][j+2]+Tmpboard[i+2][j]+Tmpboard[i+2][j+1]+Tmpboard[i+2][j+2];
                if(sum!=2){
                    if(sum==3){
                        board[i][j]=1;
                    }else if( sum>3 || sum<2 ){
                        board[i][j]=0;
                    };
                };
            };
        };
        
    }
};

9dea0936님의 댓글

  • 익명
  • 작성일
class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        cp = copy.deepcopy(board)
        dir = [
            [1, 0],
            [1, 1],
            [0, 1],
            [-1, 1],
            [-1, 0],
            [-1, -1],
            [0, -1],
            [1, -1]
        ]
        ylen = len(board)
        xlen = len(board[0])
        for y in range(ylen):
            for x in range(xlen):
                cnt = 0
                for i in range(len(dir)):
                    ny = y + dir[i][0]
                    nx = x + dir[i][1]
                    if ny < 0 or ny >= ylen or nx < 0 or nx >= xlen: 
                        continue
                    if cp[ny][nx] == 1:
                        cnt += 1 
                if cp[y][x] == 1:
                    if cnt < 2 or cnt > 3:
                        board[y][x] = 0
                if cp[y][x] == 0:
                    if cnt == 3:
                        board[y][x] = 1
        return board
전체 410 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 544 명
  • 오늘 방문자 2,005 명
  • 어제 방문자 9,517 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,597 명
알림 0