[LeetCode] 289. Game of Life

김민우·2023년 2월 6일
0

알고리즘

목록 보기
133/189

- Problem

289. Game of Life

단순 구현문제다.


- 내 풀이

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:

        def check_live_neighbors(y: int, x: int) -> int:
            return sum(board[dy+y][dx+x] for dx, dy in D if 0 <= dx + x < N and 0 <= dy + y < M)

        def judge_state(n: int, is_alive: bool) -> int:
            if (is_alive and 2 <= n <= 3) or (not is_alive and n == 3):
                return 1
            
            return 0   

        D = ((-1, -1), (-1, 0), (-1, 1), (1, 0), (1, 1), (1, -1), (0, -1), (0, 1))
        M, N = len(board), len(board[0])
        new_board = [[0 for _ in range(N)] for _ in range(M)]

        for i in range(M):
            for j in range(N):
                live_neighbors = check_live_neighbors(i, j)
                new_board[i][j] = judge_state(live_neighbors, board[i][j])

        for i in range(M):
            for j in range(N):
                board[i][j] = new_board[i][j]

- 결과

  • 시간 복잡도: O(MN)
  • 공간 복잡도: O(MN)
profile
Pay it forward.

0개의 댓글