289. Game of Life
来源:互联网 发布:小袄淘宝网,金丝绒的 编辑:程序博客网 时间:2024/05/22 13:09
According to the Wikipedia's article: "The Game of Life, also known simply asLife, 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 statelive (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.
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
再起一个vec很好做,只是不合乎要求。
代码:
//static int m[100][100];class Solution {public: int countnum (int m, int n,vector<vector<int>> temp) { int count=0; for(int i=m-1;i<m+2; ++i) for(int j=n-1;j<n+2;++j) count+=temp[i][j]; return count-temp[m][n]; } void gameOfLife(vector<vector<int>>& board) { int m=board.size(); if(m==0) return; int n=board[0].size(); vector< vector<int> > temp(m+2,vector<int> (n+2,0)); for(int i=0 ;i<m ;++i) for(int j=0; j<n ;++j) { temp[i+1][j+1]=board[i][j]; } for(int i=0;i<m ;++i) { for( int j = 0; j<n ;++j) { int count=countnum(i+1,j+1,temp); if(board[i][j]==0&&count==3) { board[i][j]=1; } else if (board[i][j]==1) { if(count<2||count>3) board[i][j]=0; } } } return ; }};
0 0
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 第十三周项目4
- 关于算法的博客、论坛推荐
- Linux共享库(动态库)与进程之间全局变量是无法共享的
- HDU 3499 分层图最短路+Trie树
- Jboss rules规则引擎 Drools 6.4.0 Final 教程(1)
- 289. Game of Life
- springMVC日期格式转换
- Clang Attributes 黑魔法小记
- *** FATAL ERROR L250: CODE SIZE LIMIT IN RESTRICTED VERSION EXCEEDED
- 2015 Objective-C 新特性
- Java并发编程与技术内幕:ThreadFactory、ThreadLocal
- 给国外老师写邮件(邮件礼仪)
- java文字识别技术(亲测,识别率很高)
- Failed to install Tomcat7 service