LeetCode 289. Game of Life


#include <vector>
#include <iostream>
using namespace std;

/*
  Given a board with m by n cells, each cell has an initial state live(1) and dead(0). Each cell interacts
  with eight neighbors. using the flollowing four rules.
  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 neightbors 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 neightbors 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.
*/

int allCounts(vector< vector<int> >& matrix, int i, int j) {
  int count = 0;
  if(i - 1 >= 0) count += matrix[i-1][j];
  if(i + 1 < matrix.size()) count += matrix[i+1][j];
  if(j - 1 >= 0) count += matrix[i][j-1];
  if(j + 1 < matrix[0].size()) count += matrix[i][j+1];
  if((i - 1 >= 0) && (j - 1 < matrix[0].size())) count += matrix[i-1][j-1];
  if((i - 1 >= 0) && (j + 1 < matrix[0].size())) count += matrix[i-1][j+1];
  if((i + 1 < matrix.size()) && (j - 1 < matrix[0].size())) count += matrix[i+1][j-1];
  if((i + 1 < matrix.size()) && (j + 1 < matrix[0].size())) count += matrix[i+1][j+1];
  return count;
}

void gameOfLife(vector< vector<int> >& matrix) {
  if(matrix.size() == 0 || matrix[0].size() == 0) return;
  vector< vector<int> > nextState(matrix.size(), vector<int>(matrix[0].size(), 0));
  for(int i = 0; i < matrix.size(); ++i) {
    for(int j = 0; j < matrix[i].size(); ++j) {
      int tmp = allCounts(matrix, i, j);
      if((matrix[i][j] == 0) && (tmp == 3)) nextState[i][j] = 1;
      if(matrix[i][j] == 1) {
        if(tmp < 2) nextState[i][j] = 0;
        else if(tmp > 3) nextState[i][j] = 0;
        else nextState[i][j] = 1;
      }
    }
  }
  matrix = nextState;
}

int main(void) {
  vector< vector<int> > matrix {
    {0, 1, 0, 1},
    {1, 0, 0, 0},
    {0, 0, 0, 0},
    {1, 1, 1, 1}};
  gameOfLife(matrix);
  for(int i = 0;  i < matrix.size(); ++i) {
    for(int j = 0; j < matrix[i].size(); ++j) {
      cout << matrix[i][j] << " ";
    }
    cout << endl;
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值