leetcode笔记: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.

二. 题目分析

题目很长,大意如下:

给定一个由0,1组成的矩阵,每一个元素表示一个细胞的存活,1存活,0死亡,其中下一次更新每个细胞的存活由上、下、左、右、左上、左下、右上、右下,八个细胞决定,存活规则如下:

当前细胞为存活状态时,当周围存活细胞不到2个时, 该细胞变成死亡状态。(模拟生命数量稀少)

当前细胞为存活状态时,当周围有2个或3个存活的细胞时, 该细胞保持原样。

当前细胞为存活状态时,当周围有3个以上的存活细胞时,该细胞变成死亡状态。(模拟生命数量过多)

当前细胞为死亡状态时,当周围恰好有3个存活细胞时,该细胞变成存活状态。 (模拟繁殖)

要求写一个函数,根据矩阵当前的状态,计算这个细胞矩阵的下一个状态。

题目要求in-place操作,考虑到每个元素都受附近8个元素的影响,必须使用一种中间状态来记录元素变化,这种中间状态应该能反应元素变化前变化后的状态。

好在题目给出了四种变化状态,比较直观地给出了思路:

状态0: 死细胞->死细胞

状态1: 活细胞->活细胞

状态2: 活细胞->死细胞

状态3: 死细胞->活细胞

对每个元素进行判断,根据附近8个元素及本身的状态可得到状态0~4中的一个,而下一个元素依然可根据上一元素的状态0~4,判断上一元素变化之前是什么状态。

而对所有元素标记状态0~4后,再一次遍历矩阵,所有元素的状态对2取余,那么状态0和2就变成死细胞,状态1和3就是活细胞,达成目的。

三. 示例代码

class Solution
{
public:
    void gameOfLife(vector<vector<int>>& board)
    {
        int rows=board.size();
        if(rows==0)
            return ;
        int colums=board[0].size();
        if(colums==0)
            return ;
        for(int i=0; i<rows; ++i)
        {
            for(int j=0; j<colums; ++j)
            {
                int sum=getNeighbor(board,rows,colums,i,j);
                if(sum==2)
                    continue;
                else if(sum==3)
                    board[i][j]=board[i][j]==0?3:1;
                else
                    board[i][j]=board[i][j]==1?2:0;
            }
        }
        for(int i=0;i<rows;++i)
        {
            for(int j=0;j<colums;++j)
                board[i][j]%=2;
        }

    }
private:
    int getNeighbor(vector<vector<int>>& board,int rows,int colums,int x,int y)
    {
        int sum=0;
        for(int i=x-1; i<x+2; ++i)
        {
            for(int j=y-1; j<y+2; ++j)
            {
                if(i==x&&j==y)
                    continue;
                if(i>=0&&i<rows&&j>=0&&j<colums&&(board[i][j]==1||board[i][j]==2))
                    ++sum;
            }
        }
        return sum;
    }
};

四. 小结

该题目在in-place的要求下,是一道有趣的题目。

时间: 2024-11-10 22:40:23

leetcode笔记:Game of Life的相关文章

leetcode笔记

leetcode 笔记 Linked List 2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a

[leetcode笔记] Remove Duplicates from Sorted List II

问题描述: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example,Given 1->2->3->3->4->4->5, return 1->2->5.Given 1->1->1->2->3, return 2-&

leetcode笔记:Pascal&amp;#39;s Triangle

一. 题目描写叙述 Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 二. 题目分析 关于帕斯卡三角形的定义,可參考:http://baike.baidu.com/link?url=qk_-urYQnO4v6v3P4BuMtCa0tMNUqJUk

[leetcode笔记] Longest Consecutive Sequence

随机挑选一题试试手气.   问题描述: Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your al

LeetCode 笔记26 Single Number II

Given an array of integers, every element appears three times except for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 没辙,智商碾压题.楼主没遇到之前就只会这种做法. public int si

[LeetCode笔记]-237-Delete Node in a Linklist

上LeetCode后做的第一道题.删除一个链表节点.两个写法.第一个8ms,第二个4ms.先这么写吧. /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ /* solution 1 // The normal one I can think immediately. void deleteNode(struct ListNode* nod

LeetCode 笔记28 Maximum Gap

Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements. You may assume all elements in the array are non-negat

leetcode笔记:2Sum

一.题目描述 基本意思是给定一组整数和一个常数target,试图在这一组数里找到两个数使得两者的和等于target,结果要求返回两个数的下标. 二.解题思路 思路一:使用暴力算法实现,这种情况下空间复杂度为O(1),但是时间复杂度为O(n^2),会超时. 思路二:使用hash表,存储每个数对应的下标,事件复杂度为O(n).这样在查找某个值存不存在只需要常数时间. //LeetCode, Two Sum // 时间复杂度O(n),空间复杂度O(n) class Solution { public:

leetcode笔记11 First Unique Character in a String

题目描述: Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. Note: You may assume the string contain only low

leetcode笔记:3Sum

一.题目描述 二.解题技巧 这道题和另外一道题Two Sum很类似,不过这道题是在数组中寻找三个数,使得其和为0,同时要求这三个数只能出现一次.如果单纯得使用暴力算法来做的话,时间复杂度为O(n^3),且很难判断这一组数是否已经出现过. 若是选择先排序,然后左右夹逼,复杂度:O(n2). 这个方法可以推广到k-sum,先排序,然后做k-2 次循环,在最内层循环左右夹逼,时间复杂度是:O(max(n*logn, n^(k-1))). 如果考虑将数组A(元素个数为n)进行升序排序,那么按照顺序将数组