LeetCode.289

来源:互联网 发布:幼儿园营养分析软件 编辑:程序博客网 时间:2024/06/05 03:15
/* 
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.

 */

#include <iostream>#include <vector>using namespace std;void gameOfLife(vector< vector<int> >& in_mod){int height = in_mod.size();    if(height == 0){        return ;     }int width = in_mod[0].size();    if(width == 0){        return ;     }int save_mod[height][width];for(int i = 0; i < height; i++){for(int j = 0; j < width; j++){//定位in_mod(i, j),初始化 save_mod[i][j] = 0;}}for(int i = 0; i < height; i++){for(int j = 0; j < width; j++){//定位in_mod(i, j),初始化 cout << save_mod[i][j] << " ";}cout << endl;}for(int i = 0; i < height; i++){for(int j = 0; j < width; j++){//定位in_mod(i, j)if(in_mod[i][j]){for(int y = -1; y < 2; y++){if(0 <= i + y && i + y < height){for(int x = -1; x < 2; x++){if(0 <= j + x && j + x < width){if(y != 0 || x != 0){save_mod[i + y][j + x]++;}}}}}}}}/*save_mod1. 1周围少于(<)2个1置02. 1周围多于(>)3个1置03. 0周围刚好(=)3个1置1 */for(int i = 0; i < height; i++){for(int j = 0; j < width; j++){//定位in_mod(i, j)if(in_mod[i][j]){if(2 <= save_mod[i][j] && save_mod[i][j] <= 3){continue;}else{in_mod[i][j] = 0;}}else{if(save_mod[i][j] == 3){in_mod[i][j] = 1;}}}}}


原创粉丝点击