Game of Life问题及解法
来源:互联网 发布:知柏地黄丸 多少钱 编辑:程序博客网 时间:2024/06/10 14:58
问题描述:
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) { int m = board.size(), n = m ? board[0].size() : 0;for (int i = 0; i < m; i++){for (int j = 0; j < n; j++){int count = 0;for (int I = max(i - 1, 0); I<min(i + 2, m); ++I)for (int J = max(j - 1, 0); J < min(j + 2, n); ++J){count += board[I][J] & 1;}if (count == 3 || count - board[i][j] == 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
- Game of Life问题及解法
- Nim Game问题及解法
- Jump Game问题及解法
- Elimination Game问题及解法
- Baseball Game问题及解法
- leetcode之Game of Life 问题
- 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
- win10应用商店无法联网(代码:0x80131505)
- 页面发生跳转但是url 不发生变化
- Android近期任务列表Recent List(Recents Screen)的实现方式
- (Android)react-native更改状态栏文字和图标颜色
- BZOJ1574: [Usaco2009 Jan]地震损坏Damage
- Game of Life问题及解法
- 随想录(c编译器的实现)
- JS取消冒泡事件
- Spring中使用JdbcTemplate的queryForObject方法,当查不到数据时会抛出如下异常:
- Redis
- 西部航空增开南北长航线,海航负债率再被肯定
- python文件练习
- Ubuntu如何查找libz.so.1属于哪个包并安装
- ofbiz实战8——实验室预约管理系统功能介绍