[leetcode] 957. Prison Cells After N Days

Description

There are 8 prison cells in a row, and each cell is either occupied or vacant.

Each day, whether the cell is occupied or vacant changes according to the following rules:

  • If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
  • Otherwise, it becomes vacant.
    (Note that because the prison is a row, the first and the last cells in the row can’t have two adjacent neighbors.)

We describe the current state of the prison in the following way: cells[i] == 1 if the i-th cell is occupied, else cells[i] == 0.

Given the initial state of the prison, return the state of the prison after N days (and N such changes described above.)

Example 1:

Input: cells = [0,1,0,1,1,0,0,1], N = 7
Output: [0,0,1,1,0,0,0,0]
Explanation: 
The following table summarizes the state of the prison on each day:
Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
Day 7: [0, 0, 1, 1, 0, 0, 0, 0]

Example 2:

Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
Output: [0,0,1,1,1,1,1,0]

Note:

  1. cells.length == 8
  2. cells[i] is in {0, 1}
  3. 1 <= N <= 10^9

分析

题目的意思是:根据上面的规则,求出第N天牢房的状态。这道题需要找规律,因为N很大的时候肯定会超时,牢房有8个状态,其中第1个和最后一个肯定是0,我们只需要找中间6个状态的规律就行了。

  • prison用来存储已经得到的状态,防止进入死循环,利用prison可以找到循环周期,然后更新N,再递归调用一遍就可以得到最终的cells的状态了
  • 主意一下mod的计算方式和递归的时候N的更新方式,我尝试把它换成N%(mod+1)结果ac不了,这个以后可以研究一下啦
  • 每一次确定下一天状态的时候,只需要确定中间的6个状态就行了

如果知道上面这些要点,就容易写出来了

代码

class Solution:
         
    def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:
        prison = {}
        for i in range(N):
            str1=str(cells)
            if(str1 in prison):
                mod=i-prison[str1]
                return self.prisonAfterNDays(cells,(N-i)%mod)
            prison[str1]=i
            t=[0]
            for i in range(1,7):
                if(cells[i-1]==cells[i+1]):
                    t.append(1)
                else:
                    t.append(0)
            t.append(0)
            cells=t
        return cells

参考文献

Python Solution
[LeetCode]957.Prison Cells After N Days 中文
957. Prison Cells After N Days

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值