0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

289. Game of Life 解答例・ポイント補足

Posted at

問題内容

有名なライフゲームの挙動を実行するプログラムを記述するもの

解答例

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

        directions = [(1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1), (0,1), (1,1)]
        
        for i in range(len(board)):
            for j in range(len(board[0])):
                live = 0                
                for x, y in directions: 
                    if ( i + x < len(board) and i + x >= 0 ) and ( j + y < len(board[0]) and j + y >=0 ) and abs(board[i + x][j + y]) == 1:
                        live += 1
                if board[i][j] == 1 and (live < 2 or live > 3):    
                    board[i][j] = -1
                if board[i][j] == 0 and live == 3:                  
                    board[i][j] = 2
        for i in range(len(board)):
            for j in range(len(board[0])):
                board[i][j] = 1 if(board[i][j] > 0) else 0
        return board

この問題のポイント

この問題で難しいのは、あるマスについて次の状態を判定し上書きする際、他のマスの判定に影響を与えないようにするところ。その点で解答例内の注目すべきところは以下の部分。

sample
abs(board[i + x][j + y]) == 1:

これによって絶対値が1になればカウントすることになる。これによって、判定の際にカウントされるべきものは1か‐1であれば良くなる。つまり、今回カウントされる中で次も生存するものと死亡するものでラベルを分けることができる。

同じような仕組みで

sample
if board[i][j] == 0 and live == 3:                  
    board[i][j] = 2

もある。これは、今回カウントされない中で次回は生存するものと死亡するものというラベル分けに役立っている。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?