289. Game of Life

来源:互联网 发布:清除文件 linux 编辑:程序博客网 时间:2024/05/22 23:23

题意: 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
0 0
原创粉丝点击