【LeetCode】 289. Game of Life
来源:互联网 发布:爱福窝在线设计软件 编辑:程序博客网 时间:2024/05/22 17:17
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?
public class Solution { public void gameOfLife(int[][] board) { int m = board.length, n = board[0].length; if (m == 0 || n == 0) { return; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int live = 0; for (int k = Math.max(i - 1, 0); k <= Math.min(i + 1, m - 1); k++) { for (int l = Math.max(j - 1, 0); l <= Math.min(j + 1, n - 1); l++) { live += board[k][l] & 1; } } live -= board[i][j]; if (board[i][j] == 1 && live >= 2 && live <= 3) { board[i][j] = 3; } if (board[i][j] == 0 && live == 3) { board[i][j] = 2; } } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { board[i][j] >>= 1; } } }}
0 0
- [leetcode] 289. Game of Life
- 289. Game of Life LeetCode
- leetcode 289. Game of Life
- [LeetCode]289. Game of Life
- LeetCode 289. Game of Life
- LeetCode *** 289. Game of Life
- 【leetcode】289. Game of Life
- LeetCode 289. Game of Life
- LeetCode-289.Game of Life
- [Leetcode]289. Game of Life
- LeetCode--289. Game of Life
- [leetcode] 289. Game of Life
- [LeetCode] 289. Game of Life
- [leetcode]289. Game of Life
- [LeetCode]289. Game of Life
- [LeetCode]289. Game of Life
- 【LeetCode】 289. Game of Life
- LeetCode 289. Game of Life
- 汇编代码存档
- 我有罪我用了1下午时间终于无师自学用C#开发了俺的领先个Android 浏览器APP我对不起java 社区
- 一款好用的下拉选择插件select2
- Masonry实现瀑布流布局
- 解决ubuntu16.10和windows10双系统时间不同步的问题
- 【LeetCode】 289. Game of Life
- css input[type=file] 样式美化,input上传按钮美化
- 树莓派获取Nodemcu温度并发送邮件预警
- 电话打入和打出的区别
- ubuntu 16.04 安装opencv 2.4.13
- CTF隐写术--安女神,我爱你!
- 文章索引~软件美化
- 趣味分析系列 | 女生罩杯型号知多少
- System.out.println引发的volatile和synchronize