1. 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. 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:

  1. Input:
  2. [
  3. [0,1,0],
  4. [0,0,1],
  5. [1,1,1],
  6. [0,0,0]
  7. ]
  8. Output:
  9. [
  10. [0,0,0],
  11. [1,0,1],
  12. [0,1,1],
  13. [0,1,0]
  14. ]

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?

解法1 将原矩阵复制下来,按照游戏规则修改原来的矩阵

  1. class Solution {
  2. public:
  3. void gameOfLife(vector<vector<int>>& board) {
  4. vector<vector<int>>tmp_board(board.begin(), board.end());
  5. int m = board.size(), n = board[0].size();
  6. for(int i = 0; i < m; ++i){
  7. for(int j = 0; j < n; ++j){
  8. int cnt = 0;
  9. for(int k = 0; k < 8; ++k){
  10. int tmp_x = i + dx[k], tmp_y = j + dy[k];
  11. if(valid(tmp_x, tmp_y, m, n) && tmp_board[tmp_x][tmp_y]){
  12. cnt++;
  13. }
  14. }
  15. if(tmp_board[i][j] == 1){
  16. if(cnt < 2 || cnt > 3){
  17. board[i][j] = 0;
  18. }else{
  19. board[i][j] = 1;
  20. }
  21. }else{
  22. if(cnt == 3)board[i][j] = 1;
  23. else board[i][j] = 0;
  24. }
  25. }
  26. }
  27. }
  28. private:
  29. int dx[8] = {-1, 0, -1, -1, 0, 1, 1, 1};
  30. int dy[8] = {0, -1, -1, 1, 1, 0, -1, 1};
  31. bool valid(int x, int y, int m, int n){
  32. if(x < 0 || x >= m || y < 0 || y >= n)return false;
  33. return true;
  34. }
  35. };

解法2 原地修改,\(O(1)\)空间复杂度。使用多个状态:

  • 0:原来是0,新的还是0
  • 1:原来是1,新的还是1
  • 2:原来是0,新的是1
  • 3:原来是1,新的是0

按照行顺序更新时,对于每个cell,左、上、左上、右上是被更新了,剩下四个没有更新,按照对应的数值统计出在原始矩阵中的数字,然后更新当前cell,最后遍历一遍,把2和3分别修改成1和0

  1. class Solution {
  2. public:
  3. void gameOfLife(vector<vector<int>>& board) {
  4. int m = board.size(), n = board[0].size();
  5. for(int i = 0; i < m; ++i){
  6. for(int j = 0; j < n; ++j){
  7. int cnt = 0;
  8. for(int k = 0; k < 4; ++k){
  9. int tmp_x = i + dx[k], tmp_y = j + dy[k];
  10. if(valid(tmp_x, tmp_y, m, n) &&
  11. (board[tmp_x][tmp_y] == 3 || board[tmp_x][tmp_y] == 1)){
  12. cnt++;
  13. }
  14. }
  15. for(int k = 4; k < 8; ++k){
  16. int tmp_x = i + dx[k], tmp_y = j + dy[k];
  17. if(valid(tmp_x, tmp_y, m, n) && board[tmp_x][tmp_y] == 1){
  18. cnt++;
  19. }
  20. }
  21. if(board[i][j] == 1){
  22. if(cnt < 2 || cnt > 3){
  23. board[i][j] = 3;
  24. }else{
  25. board[i][j] = 1;
  26. }
  27. }else{
  28. if(cnt == 3)board[i][j] = 2;
  29. else board[i][j] = 0;
  30. }
  31. }
  32. }
  33. for(int i = 0; i < m; ++i){
  34. for(int j = 0; j < n; ++j){
  35. if(board[i][j] == 2)board[i][j] = 1;
  36. else if(board[i][j] == 3)board[i][j] = 0;
  37. }
  38. }
  39. }
  40. private:
  41. int dx[8] = {-1, 0, -1, -1, 0, 1, 1, 1};
  42. int dy[8] = {0, -1, -1, 1, 1, 0, -1, 1};
  43. bool valid(int x, int y, int m, int n){
  44. if(x < 0 || x >= m || y < 0 || y >= n)return false;
  45. return true;
  46. }
  47. };

【刷题-LeetCode】289. Game of Life的更多相关文章

  1. LeetCode刷题------------------------------LeetCode使用介绍

    临近毕业了,对技术有种热爱的我也快步入码农行业了,以前虽然在学校的ACM学习过一些算法,什么大数的阶乘,dp,背包等,但是现在早就忘在脑袋后了,哈哈,原谅我是一枚菜鸡,为了锻炼编程能力还是去刷刷Lee ...

  2. [刷题] Leetcode算法 (2020-2-27)

    1.最后一个单词的长度(很简单) 题目: 给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度. 如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词. 如果不存在 ...

  3. bash 刷题leetcode

    题目一: 给定一个文本文件 file.txt,请只打印这个文件中的第十行. 示例: 假设 file.txt 有如下内容: Line 1 Line 2 Line 3 Line 4 Line 5 Line ...

  4. 【刷题-LeetCode】307. Range Sum Query - Mutable

    Range Sum Query - Mutable Given an integer array nums, find the sum of the elements between indices ...

  5. 【刷题-LeetCode】306. Additive Number

    Additive Number Additive number is a string whose digits can form additive sequence. A valid additiv ...

  6. 【刷题-LeetCode】304. Range Sum Query 2D - Immutable

    Range Sum Query 2D - Immutable Given a 2D matrix matrix, find the sum of the elements inside the rec ...

  7. 【刷题-LeetCode】300. Longest Increasing Subsequence

    Longest Increasing Subsequence Given an unsorted array of integers, find the length of longest incre ...

  8. 【刷题-LeetCode】264. Ugly Number II

    Ugly Number II Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose ...

  9. 【刷题-LeetCode】275. H-Index II

    H-Index II Given an array of citations sorted in ascending order (each citation is a non-negative in ...

随机推荐

  1. 好奇怪啊,如果邮箱JSON格式的字符串不是在一行上,那么转为JSON将转换不成功,估计是数据格式有问题吧

    好奇怪啊,如果邮箱JSON格式的字符串不是在一行上,那么转为JSON将转换不成功,估计是数据格式有问题吧, 打印出的数据必须是如下的在一行的字符串,才可以转换为JSON格式成功.

  2. JAVA判断IP是否是内网IP

    /** * 私有IP: * A类  10.0.0.0-10.255.255.255   * B类  172.16.0.0-172.31.255.255   * C类  192.168.0.0-192. ...

  3. 二叉树c++实现

    !!版权声明:本文为博主原创文章,版权归原文作者和博客园共有,谢绝任何形式的 转载!! 作者:mohist --- 欢迎指正--- 二叉树特点: 要么为空树:要么,当前结点的左孩子比当前结点值小,当前 ...

  4. c++设计模式概述之观察者

    代码写的不够规范,目的是缩短篇幅,实际情况请不要这样做 1.概述 观察者模式,类比生活中的场景,比如看电影,观众对播放的内容有不同的反应, 再比如订阅,公众号订阅,只要你订阅了其公众号,你就会收到其推 ...

  5. fedora之自动寻找命令并提示安装PackageKit-command-not-found

    fedora 1.比如,我要用clang 命令编译代码,但是没有该指令.比如: clang main.cxx -o main 2.那么,输入未知命令,希望fedora会自动寻找相对应的包,再并提示安装 ...

  6. 【九度OJ】题目1474:矩阵幂 解题报告

    [九度OJ]题目1474:矩阵幂 解题报告 标签(空格分隔): 九度OJ http://ac.jobdu.com/problem.php?pid=1474 题目描述: 给定一个n*n的矩阵,求该矩阵的 ...

  7. 【LeetCode】932. Beautiful Array 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 构造法 递归 相似题目 参考资料 日期 题目地址:h ...

  8. 【LeetCode】Pascal's Triangle II 解题报告

    [LeetCode]Pascal's Triangle II 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/pascals-tr ...

  9. 【LeetCode】284. Peeking Iterator 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/peeking-i ...

  10. Are Loss Functions All the Same?

    目录 概 主要内容 一些假设 损失函数 损失函数的统计性质 收敛速度 分类的界 Rosasco L, De Vito E, Caponnetto A, et al. Are loss function ...