Game of Life
来源:互联网 发布:php一年工作经验工资 编辑:程序博客网 时间:2024/06/12 20:33
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?
方法:考虑位标记,因为题目中只出现过0和1标记,因此可以用位操作。
class Solution {public: void gameOfLife(vector<vector<int>>& board) { if(board.size() == 0) return ; const int mov_x[8]={-1,0,1,-1,1,-1,0,1}; const int mov_y[8]={-1,-1,-1,0,0,1,1,1}; int i = 0 , j = 0; for(int i = 0 ; i < board.size(); ++i){ for(int j = 0 ; j < board[0].size(); ++j){ int count_1 = 0; int new_state; for(int k = 0 ; k < 8 ;++k){ if(i+mov_y[k]>=0&&i+mov_y[k]<board.size()&&j+mov_x[k]>=0&&j+mov_x[k]<board[0].size()){ if(board[i+mov_y[k]][j+mov_x[k]]&1==1) ++count_1; } } if(count_1<2) new_state = 0; else if(count_1 == 2) new_state = board[i][j]; else if(count_1 ==3) new_state = 1; else new_state = 0; board[i][j] = board[i][j]|(new_state<<1); } } for(int i = 0 ; i < board.size(); ++i){ for(int j = 0 ; j < board[0].size(); ++j){ board[i][j]=(board[i][j]>>1); } } }};
- Game of Life
- Game Of Life
- LeetCode:Game of Life
- LeetCode: Game of Life
- Game of Life
- leetcode289 : Game of Life
- 【LeetCode】Game of Life
- Game of Life
- Game of Life
- LeetCode Game of Life
- Leetcode Game of Life
- Game of Life
- Game of Life
- [289]Game of Life
- [LeetCode] Game of Life
- Game Of Life
- LeetCode -- Game of Life
- 【leetcode】Game of Life
- 欢迎使用CSDN-markdown编辑器
- AngularJs ng-route路由详解
- HTML5本地存储
- Excel(2):按上下左右键不是单元格在动,而是整个屏幕都在动
- centos 版本阿里云上配置svn服务器,eclipse连接的时候提示:由于目标计算机积极拒绝,无法连接
- Game of Life
- Python 中的闭包 —— Closure
- 如何关闭和打开eclipse的代码里的错误提醒
- 05-树7 堆中的路径 (25分)
- 记录用unity开发hololens时遇到的几个坑
- 面向对象设计的SOLID原则
- Ensemble Learning: Bootstrap aggregating (Bagging) & Boosting & Stacked generalization (Stacking)
- NS3仿真wifi网络环境
- HDU1720 A+B Coming