在python中查找k天后监狱牢房状态的程序
假设我们有一个二进制列表(列表中的1s和0s)和另一个值k。每个以num为单位的值表示监狱牢房的状态,其中1表示占用的牢房,0表示空的牢房。每天,当一个单元格中有两个相邻的单元格都被占用或都空着时,它就会被占用。否则,它将变为空。因此,我们必须在k天后找到监狱牢房的状态。
因此,如果输入像nums=[1,0,1,0,0,0,0,0]k=1,则输出将是[0,1,1,1,0,1,1,1,0],因为我们注意到第一个索引和最后一个索引永远不会被占用,因为它们永远不会有2个邻居。
让我们看下面的实现以更好地理解:
示例
import copy
class Solution:
def next_day_state(self, cells):
new_cells = copy.copy(cells)
new_cells[0] = 0
new_cells[7] = 0
for j in range(1, 7):
if cells[j - 1] == cells[j + 1]:
new_cells[j] = 1
else:
new_cells[j] = 0
return new_cells
def solve(self, cells, N):
seen = dict() flag, i = False, 0
while i < N:
ns = self.next_day_state(cells)
if tuple(ns) not in seen:
seen[tuple(ns)] = True
else:
flag = True
break
cells = ns
i += 1
if flag:
N = N % len(seen)
i = 0
while i < N:
ns = self.next_day_state(cells)
i += 1
cells = ns
return cells
ob = Solution()nums = [1, 0, 1, 0, 0, 0, 0, 0]
k = 1
print(ob.solve(nums, k))输入值
[4, 7, 2, 5], 6
输出结果
[0, 1, 1, 0, 1, 1, 1, 0]