289. Game of Life
题目:
https://leetcode.com/problems/game-of-life/
难度 : Medium
直接一上来就没有考虑solve it in-place,考虑的是便利,简直是born for 便利
首先我把board拓宽了,宽,高各增加了两排。
因为这样求neighbor方便,针对原来的borad,现在新的big 对于 1 -> n-1 的部分
全都有八个neighbor,用了一个2d array来记录nbrs,再根据当下的nbr来判断更新,因为不能一边在board上loop一边更新.
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if board == [[]] : return
row = len(board)
col = len(board[0])
nbrs = [[0 for j in range(col)] for i in range(row)]
self.big = [[ 0 for j in range(col+2) ] for i in range(row+2)]
for i in range(1,row+1):
for j in range(1,col+1):
self.big[i][j] = board[i-1][j-1]
for i in range(1,row+1):
for j in range(1,col+1):
nbrs[i-1][j-1] = self.liveNeighbors(self.big,i,j)
for i in range(row):
for j in range(col):
if board[i][j] == 1:
if nbrs[i][j] < 2:
board[i][j] = 0
elif nbrs[i][j] == 2 or nbrs[i][j] == 3:
board[i][j] = 1
else:
board[i][j] = 0
else:
if nbrs[i][j] == 3:
board[i][j] = 1
def liveNeighbors(self,big,i,j):
return self.big[i-1][j-1] + self.big[i-1][j] + self.big[i-1][j+1] + self.big[i][j-1] + self.big[i][j+1] + self.big[i+1][j-1] + self.big[i+1][j] + self.big[i+1][j+1]
谷歌了一下,大家都用到了temp 2d array嘛,哼(ˉ(∞)ˉ)唧。好吧,空间复杂度比我小。
289. Game of Life
题目:
https://leetcode.com/problems/game-of-life/
难度 : Medium
直接一上来就没有考虑solve it in-place,考虑的是便利,简直是born for 便利
首先我把board拓宽了,宽,高各增加了两排。
因为这样求neighbor方便,针对原来的borad,现在新的big 对于 1 -> n-1 的部分
全都有八个neighbor,用了一个2d array来记录nbrs,再根据当下的nbr来判断更新,因为不能一边在board上loop一边更新.
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if board == [[]] : return
row = len(board)
col = len(board[0])
nbrs = [[0 for j in range(col)] for i in range(row)]
self.big = [[ 0 for j in range(col+2) ] for i in range(row+2)]
for i in range(1,row+1):
for j in range(1,col+1):
self.big[i][j] = board[i-1][j-1]
for i in range(1,row+1):
for j in range(1,col+1):
nbrs[i-1][j-1] = self.liveNeighbors(self.big,i,j)
for i in range(row):
for j in range(col):
if board[i][j] == 1:
if nbrs[i][j] < 2:
board[i][j] = 0
elif nbrs[i][j] == 2 or nbrs[i][j] == 3:
board[i][j] = 1
else:
board[i][j] = 0
else:
if nbrs[i][j] == 3:
board[i][j] = 1
def liveNeighbors(self,big,i,j):
return self.big[i-1][j-1] + self.big[i-1][j] + self.big[i-1][j+1] + self.big[i][j-1] + self.big[i][j+1] + self.big[i+1][j-1] + self.big[i+1][j] + self.big[i+1][j+1]
谷歌了一下,大家都用到了temp 2d array嘛,哼(ˉ(∞)ˉ)唧。好吧,空间复杂度比我小。
原来还有高人用位运算啊,待研究。
网友评论