您的位置:首页 > Web前端

leetcode -- Game of Life -- 有trick,要看

2015-12-10 20:21 274 查看
https://leetcode.com/problems/game-of-life/

参考http://bookshadow.com/weblog/2015/10/04/leetcode-game-life/

位运算(bit manipulation)

由于细胞只有两种状态0和1,因此可以使用二进制来表示细胞的生存状态

更新细胞状态时,将细胞的下一个状态用高位进行存储

全部更新完毕后,将细胞的状态右移一位

class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
dx = (1, 1, 1, 0, 0, -1, -1, -1)
dy = (1, 0, -1, 1, -1, 1, 0, -1)
for x in range(len(board)):
for y in range(len(board[0])):
lives = 0
for z in range(8):
nx, ny = x + dx[z], y + dy[z]
lives += self.getCellStatus(board, nx, ny)
if lives + board[x][y] == 3 or lives == 3: # cell是live只有两种情况,neibor有3个live,i.e. lives == 3.或者neibor有2个live,并且原来是live,即01,所以加起来等于3.
board[x][y] |= 2#给高位赋值1
for x in range(len(board)):
for y in range(len(board[0])):
board[x][y] >>= 1#右移到高位
def getCellStatus(self, board, x, y):
if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]):
return 0
return board[x][y] & 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: