Game of Life

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):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. 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. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
Output: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]
/* 生命游戏:
 * 对于活细胞: 周围(8邻域)有2或者3个或细胞 该细胞生存 否则死亡
 * 对于死细胞: 周围有3个活细胞则复活
 *
 * 该函数对当前状态进行一次更新
 * 由于不用额外空间,可以用状态转移表示:(既能完成更新又能得知更新之前的状态) 最后再取余得最终状态(即对于余数为0下一回合都是死, 否则为生)
 * 状态:
 * 注意0,1未更新前的状态与题目要求一致为0, 1 然后定下2,3状态
 * 0  death->death
 * 1  live->live
 * 2  live->death
 * 3  death->live
 *
 * */
class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int row=board.size(), col=board[0].size();
        // 定义移动方向的数组 通过x[k] y[k]得到移动方向
        int dx[]={0,  0, 1, -1, 1, -1,  1, -1};
        int dy[]={1, -1, 0,  0, 1, -1, -1,  1};
        for(int i=0;i<row;i++){
            for(int j=0;j<col;j++){
                int cnt=0;// 扫描八邻域统计当前为活的细胞(状态1 2)
                for(int k=0;k<8;k++){
                    int x=i+dx[k], y=j+dy[k];
                    if(x>=0 && x<row && y>=0 && y<col
                    && (board[x][y]==1 || board[x][y]==2))  cnt++;
                }
                //根据活细胞的个数进行状态转换
                if(board[i][j]==0 && cnt==3)    board[i][j]=3;
                if(board[i][j]==1 && (cnt>3 || cnt<2))  board[i][j]=2;
            }
        }
        // 根据状态得到更新后的结果
        for(int i=0;i<row;i++) {
            for (int j = 0; j < col; j++) {
                board[i][j] %= 2;
            }
        }
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值