289. Game of Life

题意: According to the 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.”

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

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

Write a function to compute the next state (after one update) of the board given its current state.

Follow up:

Could you solve it in-place? Remember that the board needs to be updated at the same time: 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 the border of the array. How would you address these problems?

思路:这题一开始理解错了,它说板子是无穷的,我以为是要把(m,n)作为(0,0)九宫格的一部分,就是可以无限延伸的感觉,但是后来发现好像大家都不是这么做的。。。。。所以下面的做法不是我的,但是这两个for循环的max和min还是用的蛮精髓的,巧妙地防止了超界,但是要注意,它是把中心的状态也加入计算的,也就是九个状态一起加入计算,高位存下一个状态,低位存的是当前状态,下次通过右移就可以完成状态的转换了,还有就是这个判断条件:(count == 4 and board[i][j]) or count == 3,当count==3时,无论board[i][j]为0还是1,下一个状态都是lives,而对于没有高位置1的细胞,下一次右移后就全置0了。

class Solution(object):
    def gameOfLife(self, board):
        """
        :type board: List[List[int]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        m = len(board)
        n = len(board[0]) if m else 0
        for i in xrange(m):
            for j in xrange(n):
                count = 0
                for row in xrange(max(i-1, 0), min(i+2, m)):
                    for col in xrange(max(j-1, 0), min(j+2, n)):
                        count += board[row][col] & 1
                if (count == 4 and board[i][j]) or count == 3:
                    board[i][j] |= 2  
        for i in xrange(m):
            for j in xrange(n):
                board[i][j] >>= 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值