[leetcode] 289. Game of Life @ python

LeetCode 289 生命游戏 Python LeetCode 289题 生命游戏: 题目描述: 根据百度百科,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在1970年发明的细胞自动机。 给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞具有一个初始状态 live(1)即为活细胞, 或 dead(0)即为死细胞。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律: 如果活细胞... 阅读详情

原题

https://leetcode.com/problems/game-of-life/
According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population…
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input:
[
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
Output:
[
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]
Follow up:

Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?

解法

遍历二维数组, 深度复制原先的数组, 计算每个状态下活的邻居的数目, 直接在board上赋值.
Time: O(m*n)
Space: O(1)

代码

class Solution:
    def gameOfLife(self, board):
        """
        :type board: List[List[int]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        if not board: return board
        row, col = len(board), len(board[0])
        prev = copy.deepcopy(board)
        for i in range(row):
            for j in range(col): 
                # if the cell is live
                if prev[i][j] == 1:
                    live = self.getLiveNeighbors(prev, i, j)
                    if live < 2 or live > 3:
                        board[i][j] = 0
                        
                # if the cell is dead
                else:
                    live = self.getLiveNeighbors(prev, i, j)
                    if live == 3:
                        board[i][j] = 1                  
                        
                    
    def getLiveNeighbors(self, prev, x, y):
        row, col = len(prev), len(prev[0])
        count = 0
        shift = [[-1,-1],[-1,0],[-1,1],[0,-1],[0,1],[1,-1],[1,0],[1,1]]
        for tup in shift:
            dx, dy = tup[0], tup[1]
            if 0 <= x+dx < row and 0 <= y+dy < col and prev[x+dx][y+dy] == 1:
                count += 1
                
        return count
                
python【力扣LeetCode算法题库】289- 生命游戏 生命游戏 根据 百度百科 ,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机。 给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态:1 即为活细胞(live),或 0 即为死细胞(dead)。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律: 如果活细胞周围八个位置的活细胞数少于两个,则... 阅读详情

相关推荐

gameoflife-python:康威在无限空间中的生命游戏用 Python 实现

康威在 Python 中的生命游戏 在无限空间中的 Python 实现。 活细胞存储在一个集合中。 为了计算下一次迭代,我们计算每个具有邻居的单元格的邻居数。 Peter Norvig 在有一个很棒的解释。 我的目标是编写一个易于理解的 Pythonic 程序(限制使用推导式)。 我正在用不同的编程语言实现生命游戏以了解它们。 你可以找到。 我喜欢/不喜欢 python 的地方 Python 语法易于阅读和编写。 命名元组、迭代器、defaultdict 和列表推导式都很棒。 编写测试真的很容易。 运行示例 python game_of_life.py 运行测试 运行python test.py 更多的 查看这个程序输出的声音: : 。

【leetcode】289.生命游戏 (三种解法开阔思路,java实现)

289. 生命游戏 难度中等 根据 百度百科 ,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机。 给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态:1 即为活细胞(live),或 0 即为死细胞(dead)。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律: 如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡; 如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活; 如果活

Viper的程序员修炼手册 1082

华为防火墙USG6600全流量日志配置指南:从流量监控到NAT日志的完整方案

本文详细介绍了华为USG6600防火墙全流量日志配置方案,涵盖流量监控、NAT日志及安全事件溯源等核心功能。通过精细化配置和性能优化技巧,帮助企业构建高效、合规的日志体系,提升网络安全运维效率。文章特别强调了日志采样与字段过滤的实用方法,适用于高流量环境下的资源优化。

gin88的博客 359

【LeetCode】第289场单周赛 --- 用中等题来骗来偷袭我这个老同志?

LeetCode第 289 场周赛题目全盘解析,小白也能看得懂!

秋刀鱼与猫的博客 1万+

基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置

ProxmoxVE是一款套开源的虚拟化管理软件,用户可通过网页的方式来管理服务器上使用kvm以及lxc技术运行的虚拟机。同时提供了一些先进功能的支持,如集群、HA等。PVE虽然是开源,却是由一个商业公司在运营、更新以及维护。...

隔壁老瓦的专栏 6336

SystemVue 链路预算、仿真分析步骤

使用SystemVue进行链路预算、频谱分析等,相对ADS更全面。

BeCourageable的博客 3853

LeetCode 289 - 生命游戏

题目描述 289. 生命游戏 解法: 讲一下这里的位操作哈: 一个int占32位,但是0、1只占一位,所有我们可以借助其余的位数来做标记。具体只用借第二位就可以, rule 1:原来是01,周围细胞存活数小于2,右移一位就是0 rule 2:原来是01,周围细胞存活数等于2或3,01或上10就是11,右移一位就是1 rule 3:原来是01,周围细胞存活数大于3,右移一位就是0 rule 4:原来...

Aries_young的博客 288

Windows/Linux双平台指南:3种方法快速释放被占用的GPU内存(含任务管理器替代方案)

本文详细介绍了在Windows和Linux双平台下快速释放被占用GPU内存的3种方法,包括任务管理器替代方案。从基础操作到高阶技巧,帮助用户彻底解决GPU内存驻留问题,提升计算资源利用率。特别适用于深度学习开发者和服务器管理员处理显存泄漏等常见问题。

j0k1l2m3n的博客 274

LeetCode 289. Game of Life--Java,Python解法

LeetCode 289. Game of Life LeetCode题解专栏:LeetCode题解 我做的所有的LeetCode的题目都放在这个专栏里,大部分题目Java和Python的解法都有。 欢迎大家关注我的专栏。 此题链接:Game of Life - LeetCode According to the Wikipedia’s article: “The Game of Life,...

个人博客 946

模型剪枝实战 | Torch-Pruning 库在YOLOv8上的应用指南

本文详细介绍了如何使用Torch-Pruning库对YOLOv8模型进行结构化剪枝,以实现模型“瘦身”。通过DepGraph(依赖图)技术自动处理层间依赖,确保剪枝安全。文章提供了从环境搭建、核心原理理解到完整剪枝流程的实战指南,并强调了剪枝后的微调与性能评估,帮助开发者在保持精度的同时显著提升模型推理速度。

weixin_29046035的博客 513

2025.03.14【读书笔记】|GWAS分析神器:BOLT-LMM工具介绍与快速安装

在生物信息学领域,全基因组关联分析(GWAS)已成为揭示遗传与疾病关系的强有力工具。BOLT-LMM作为一款专为大规模样本量设计的GWAS分析工具,将极大地提高研究人员的工作效率。大家好,今天我们来聊聊一个非常强大的生物信息学工具——BOLT-LMM。它是基于线性混合模型(LMM)的全基因组关联分析(GWAS)分析工具,通过快速的方差近似方法在计算效率上实现了显著的提升。BOLT-LMM的高效性能使其成为大规模样本GWAS分析的理想选择,它将进一步推动生物信息学和遗传学研究的发展。

1103

[leetcode] 289. Game of Life

Description According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.” Given a board ...

Learning from the mistakes 266

Proxmox VE 9 更换源

创建一键更换Proxmox VE 9.0源的Bash脚本,实现快速替换软件源。脚本需包含订阅提醒关闭功能,兼容Proxmox VE 9.0系统,执行命令为bash /proxmox_9.0_Repo.sh。该工具可简化源配置过程,自动处理系统更新源替换及订阅提示屏蔽,适合需要快速配置Proxmox环境的用户使用。

极致,细节 5025

Leetcode 289. Game of Life

【代码】Leetcode 289. Game of Life。

小白菜又菜 363

一文吃透 SAP HANA SDA:把分散数据当作本地数据来用的那把钥匙

摘要:SAP HANA SDA(Smart Data Access)技术详解:150字精要 SAP HANA SDA是一种数据虚拟化技术,允许在不复制数据的情况下访问远端数据源。核心功能包括: 通过Remote Source定义连接配置 创建Virtual Table作为本地代理 支持谓词下推优化查询性能 与SDI技术协同工作扩展数据集成能力 典型应用场景包括: 跨系统联邦查询 冷热数据分层管理 混合云数据整合 远程表复制(RTR)实现近实时数据同步 实施要点: 需关注适配器能力差异 合理运用查询下推优化

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 340

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【LeetCode】289. Game of Life 解题报告(Python)

【LeetCode】289. Game of Life 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/game-of-life/description/ 题目描述: According to the Wikipedia’s a...

负雪明烛 3815

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

[LeetCode Python3] 289. Game of Life

Python3 Solution: class Solution: def numofLife(self, board, i, j): count = 0 # 上 if i > 0: if board[i-1][j] == 1 or board[i-1][j] == 2: count += 1 # 下 if i < len(board)-1:

xvrixingkong的博客 187

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

[LeetCode] 289. Game of Life 生命游戏

According to theWikipedia's article: "TheGame of Life, also known simply asLife, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." Given aboardwithmbyn...

weixin_30872867的博客 298

LeetCode-4.2-289-M-生命游戏(Game of Life)

文章目录思路-wait解法 根据 百度百科 ,生命游戏,简称为生命,是英国数学家约翰·何顿·康威在 1970 年发明的细胞自动机。 给定一个包含 m × n 个格子的面板,每一个格子都可以看成是一个细胞。每个细胞都具有一个初始状态:1 即为活细胞(live),或 0 即为死细胞(dead)。每个细胞与其八个相邻位置(水平,垂直,对角线)的细胞都遵循以下四条生存定律: 如果活细胞周围八个位置的活细...

Heorin X的博客 344

289. Game of Life刷题笔记

问题描述 签到题,拿两个队列来存放要改变的值即可 LeetCode代码: 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])

weixin_44737922的博客 394

python leetcode 289. Game of Life

class Solution(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ ...

Neekity的博客 235

【leetcode】289. Game of Life

题目如下: 解题思路:因为本题要求的是直接在输入的数组上面修改,而且细胞的生死转换是一瞬间的事情,所以需要引入两个中间状态,待死和待活。这两个中间状态用于在四条规则判断的时候是“活”和“死”,但是呈现在最终的结果是“死”和“活”。 代码如下: class Solution(object): def getLiveCount(self,board,x,y): ...

weixin_33871366的博客 109

【LeetCode】73. Set Matrix Zeroes 解题报告(Python & C++)

【LeetCode】73. Set Matrix Zeroes 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/set-matrix-zeroes/description/ 题目描述: Given a m x n matrix,...

负雪明烛 1887

面试笔试杂项积累-leetcode 286-290

289.289-Game of Life-Difficulty: Medium According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Ho

wolf96的专栏 1022
上一篇: [leetcode] 253. Meeting Rooms II @ python
下一篇: [leetcode] 53. Maximum Subarray @ python
闲庭信步的空间
博客等级 码龄9年 86粉丝 416原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值