LeetCode 289. Game of Life

来源:互联网 发布:淘宝分类模块代码 编辑:程序博客网 时间:2024/05/22 14:17


#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;  }}


0 0