【数组】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):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. 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.

Follow up:

  1. 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.
  2. 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?

思路:

这里我们假设对于某个点,值的含义为

0 : 上一轮是0,这一轮过后还是0
1 : 上一轮是1,这一轮过后还是1
2 : 上一轮是1,这一轮过后变为0
3 : 上一轮是0,这一轮过后变为1

这样,对于一个节点来说,如果它周边的点是1或者2,就说明那个点上一轮是活的。最后,在遍历一遍数组,把我们编码再解回去,即0和2都变回0,1和3都变回1,就行了。

/**
 * @param {number[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
var gameOfLife = function(board) {
    var m=board.length,n=board[0].length;

    for(var i=0;i<m;i++){
        for(var j=0;j<n;j++){
            var lives=0;
            if(i>0){
                lives+=board[i-1][j]==1||board[i-1][j]==2?1:0;
            }
            if(i<m-1){
                lives+=board[i+1][j]==1||board[i+1][j]==2?1:0;
            }
            if(j>0){
                lives+=board[i][j-1]==1||board[i][j-1]==2?1:0;
            }
            if(j<n-1){
                lives+=board[i][j+1]==1||board[i][j+1]==2?1:0;
            }
            if(i>0&&j>0){
                lives+=board[i-1][j-1]==1||board[i-1][j-1]==2?1:0;
            }
            if(i>0&&j<n-1){
                lives+=board[i-1][j+1]==1||board[i-1][j+1]==2?1:0;
            }
            if(i<m-1&&j>0){
                lives+=board[i+1][j-1]==1||board[i+1][j-1]==2?1:0;
            }
            if(i<m-1&&j<n-1){
                lives+=board[i+1][j+1]==1||board[i+1][j+1]==2?1:0;
            }
            if(board[i][j] == 0 && lives == 3){
                board[i][j] = 3;
            } else if(board[i][j] == 1){
                if(lives < 2 || lives > 3)
                    board[i][j] = 2;
            }
        }
    }

     for(var i = 0; i < m; i++){
        for(var j = 0; j < n; j++){
            board[i][j] = board[i][j] % 2;
        }
    }
};
时间: 2024-12-25 05:51:27

【数组】Game of Life的相关文章

移除数组中第一个负数后的所有负数

scala> val a = ArrayBuffer[Int](1, 2,3, 5, -1, 2, -3, -5) a: scala.collection.mutable.ArrayBuffer[Int]= ArrayBuffer(1, 2, 3, 5, -1, 2, -3 , -5)   scala> :paste // Entering paste mode (ctrl-D tofinish)   var foundFirstNegative = false val keepIndexes

NumPy基础:数组和失量计算

NumPy : Numerical Python,是高性能科学计算和数据分析的基础包. 部分功能: ndarray:一个具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组: 用于对整组数据进行快速运算的标准数学函数(无需编写循环): 用于读写磁盘数据的工具以及用于操作内存映射文件的工具: 线性代数.随机数生成以及傅里叶变换功能: 用于集成C.C++.Fortran等语言编写的代码工具: 大部分数据分析应用关注的功能: 用于

Matlab - 求数组的零值与过零点索引

function zeroindex=pickzero(x)%找出数组的零值及过零点(正负相交处,可能偏离0)m = length(x);x1=x(1:m-1);x2=x(2:m);indz = find(x==0); %zero pointindzer = find(x1.*x2<0); %negative/positiven=length(indzer);for i=1:n if abs(x(indzer(i)))>abs(x(indzer(i)+1)) indzer(i)=indzer(

Java中数组的概念

1.什么是二维数组?有几种表达方式?分别是什么? 答:多维数组即数组的数组,即数组的元素也是数组. 例:int[] [] a = {{1},{1,2},{1,2,3}}; 有三种方式 1).int [] [] a;  2).int [] a1 [];  3).int a2 [] []; *强烈推荐用第1种,不容易混淆a的数据类型: 2.多维数组的创建过程是什么? 答: 例:int [] [] a = new int [2] []; a[0] = {1,2,3}; a[1] = {4,5,6};

ES6之主要知识点(六)数组

引自http://es6.ruanyifeng.com/#docs/array 1.扩展运算符(...) 扩展运算符(spread)是三个点(...).它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列. 该运算符主要用于函数调用. function push(array, ...items) { array.push(...items); } function add(x, y) { return x + y; } var numbers = [4, 38]; add(...n

数组、字符串、集合

数组与集合的转换.数组与字符串的转换 ========数组变集合 String[] arr = {"abc","cc","kkkk"}; //把数组变成list集合有什么好处? /* 可以使用集合的思想和方法来操作数组中的元素. 注意:将数组变成集合,不可以使用集合的增删方法. 因为数组的长度是固定. contains. get indexOf() subList(); 如果你增删.那么会产生UnsupportedOperationExcepti

c#数组的count()和length的区别

C# 数组中 Length 表示数组项的个数,是个属性. 而 Count() 也是表示项的个数,是个方法,它的值和 Length 一样.但实际上严格地说 Count() 不是数组的内容,而是 IEnumerable 的内容.这也是为什么 C# 2.0 时数组不能用 Count(),而 3.0 后就可以用 Count() 的原因. 对于数组,据说用 Length 快于 Count(). 所以一般情况:数组我用 Length,IEnumerable(比如 List)我用 Count().

Falsy Bouncer(过滤数组假值)

Falsy Bouncer 过滤数组假值 (真假美猴王) 删除数组中的所有假值. 在JavaScript中,假值有false.null.0."".undefined 和 NaN. function bouncer(arr) { // 请把你的代码写在这里 return arr.filter(function(a){ return !!a; }); } bouncer([false, null, 0, NaN, undefined, ""]); 本来也不会,参考了别人

最大连续子数组,线性时间解法

思想: 经过分析可得,若子数组和为负数就已经代表这个子数组不可能为最大子数组了,相反若子数组和为正,则将最大的和比较出来便可. 故可直接遍历该数组一旦子数组和已为负数,则置为0,否则与之前的最大值进行比较,得出目前最大值. 上代码: #include<iostream> using namespace std; int getMax(int *arr,int n,int start,int end){ int max; int firstmax = arr[0]; max = arr[0];

HDU 5542 The Battle of Chibi dp+树状数组

题目:http://acm.hdu.edu.cn/showproblem.php?pid=5542 题意:给你n个数,求其中上升子序列长度为m的个数 可以考虑用dp[i][j]表示以a[i]结尾的长度为j的上升子序列有多少 裸的dp是o(n2m) 所以需要优化 我们可以发现dp的第3维是找比它小的数,那么就可以用树状数组来找 这样就可以降低复杂度 #include<iostream> #include<cstdio> #include<cstring> #include