289. Game of Life
来源:互联网 发布:高考英语短语软件 编辑:程序博客网 时间:2024/05/01 22:59
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.
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
BFS
public class Solution { public void gameOfLife(int[][] board) { for(int i=0;i<board.length;i++){ for(int j=0;j<board[0].length;j++){ int count = 0; if(i!=0){ if(j!=0){ count+=board[i-1][j-1]%2; } count+=board[i-1][j]%2; if(j!=board[0].length-1){ count+=board[i-1][j+1]%2; } } if(j!=0){ count+=board[i][j-1]%2; } if(j!=board[0].length-1){ count+=board[i][j+1]%2; } if(i!=board.length-1){ if(j!=0){ count+=board[i+1][j-1]%2; } count+=board[i+1][j]%2; if(j!=board[0].length-1){ count+=board[i+1][j+1]%2; } } if(board[i][j]==1){ if(count<2||count>3)board[i][j]=3; }else{ if(count==3)board[i][j]=2; } } } for(int i=0;i<board.length;i++){ for(int j=0;j<board[0].length;j++){ if(board[i][j]==3)board[i][j]=0; if(board[i][j]==2)board[i][j]=1; } } }}
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
- 我为什么信耶稣
- 《被黑暗罪恶辖制和蒙蔽的人啊快来…
- 织梦dede修改文章默认来源责任编辑及作者
- “DropDownList1”有一个无效 S…
- 浪漫海南5天4夜品质双人贵宾卷,中国国际旅行社的团,协办 海南旅游发展联盟会 有去过的吗?
- 289. Game of Life
- 《忍耐的功课》
- 电脑里的屏幕保护程序有什么用处
- socket实现TCP通信_TCP连接android与单片机(2016_03_21)
- 《愿神赐我们越来越清晰的圣灵的感…
- 结婚买房子房产证是写谁的名字
- Asp.net输入年的控件
- Python 标准库 urllib2 的使用细节(2.6版本)
- 手机主服务器访问速度异常咋办?网页访问异常?资源下载速度异常?怎么回事?求高手指教~!