面试150 生命游戏

思路

深度优先遍历的思路,对当前细胞八个方向进行遍历,统计存活的细胞,并通过标记修改board数组,如果细胞死亡则标记为-1,细胞复活标记为2。再次遍历数组,然后根据标记修改数组即可

python 复制代码
class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        m=len(board)
        n=len(board[0])
        directions=[(-1,0),(0,-1),(0,1),(1,0),(1,1),(-1,1),(-1,-1),(1,-1)]

        def dfs(i,j):
            count=0
            for x,y in directions:
                new_x=x+i 
                new_y=y+j 
                if 0<=new_x<m and 0<=new_y<n and abs(board[new_x][new_y])==1:
                    count+=1
            return count

        for i in range(m):
            for j in range(n):
                live=dfs(i,j)
                if board[i][j]==1 and live<2:
                    board[i][j]=-1
                elif board[i][j]==1 and live>3:
                    board[i][j]=-1
                elif board[i][j]==0 and live==3:
                    board[i][j]=2
        for i in range(m):
            for j in range(n):
                if board[i][j]<0:
                    board[i][j]=0
                elif board[i][j]>0:
                    board[i][j]=1                

值得注意的是,abs(boardnew_xnew_y)==1,是为了正确统计当前细胞的邻居原本是"活"的数量。因为在原地修改的时候-1表示原来是活的,下一个状态要变成死

相关推荐
利威尔xu1 小时前
2026-11-25-Go-panic-recover面试
面试·golang
Navigator_Z1 小时前
LeetCode //C - 1326. Minimum Number of Taps to Open to Water a Garden
c语言·算法·leetcode
Rain的Java大神之路1 小时前
DTO、VO、PO 到底要不要拆?这场 Java 分层之争,今天一次讲透
java·后端·面试
Moment1 小时前
怎么给客户讲清本体、知识图谱和大模型的关系
前端·后端·面试
jasmine02442 小时前
GitHub 开源背单词游戏:四六级考研词库,拼写正确就能攻击
游戏·github·工具类
ShineWinsu12 小时前
对于Qt:信号量(QSemaphore)的解析
c++·qt·面试·笔试·客户端·线程安全·信号量
Rain的Java大神之路14 小时前
10万QPS订单系统:缓存、ES、MQ三道连环题,我把踩过的坑一次讲透
java·后端·面试
Rain的Java大神之路14 小时前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
Rocky Ding*17 小时前
【三年面试五年模拟】2026-09-23 恒生电子AI Agent应用开发岗面试全解析
人工智能·深度学习·机器学习·面试·职场和发展·aigc·ai-native
nice_lcj52019 小时前
Bean 的作用域:单例、原型及特殊作用域
java·spring·面试·原型·单例·bean作用域