Life Game(二维)
题目描述
Definitions:
Life is really a simulation, not a game with players. It takes place on unbounded rectangular grid in which each cell can either be occupied by an organism or not. Occupied cells are called alived; unoccupied cells are called dead. Which cells are alive changes from generation to generation according to the number of neighboring cells that are alive, as follows transition rules:
(1) The neighbors of a given cell are the eight cells that touch it vertically, horizontally, or diagonally.
(2) If a cell is alive but either has no neighboring cells alive or only one alive, then in the next generation the cell dies of loneliness.
(3) If a cell is alive and has four or more neighboring cells also alive, then in the next generation the cell dies of overcrowding.
(4) A living cell with either two or three living neighbors remains alive in the next generation.
(5) If a cell is dead, then in the next generation it will become alive if it has exactly three neighboring cells, no more or fewer, that are already alive. All other dead cells remain dead in the next generation.
(6) All births and deaths take place at exactly the same time.
(7) The size of grid is 20 * 60
输入/输出
Input: the coordinates of living cells (Terminate the list with the special pair -1 -1).
The number (n) of generation. (n=0 means the initial Grid)
Output: the next n generations of the grid.
#include <iostream>
using namespace std;
class Life
{
public:
void initialize()
{
for (int row = 0; row <= 20 + 1; row++)
{
for (int col = 0; col <= 60 + 1; col++)
{
grid[row][col] = 0;
}
}
int row, col;
cin >> row >> col;
while (row != -1 || col != -1)
{
grid[row][col] = 1;
cin >> row >> col;
}
}
void print()
{
for (int row = 1; row <= 20; row++)
{
for (int col = 1; col <= 60; col++)
{
if (grid[row][col] == 1)
cout << '*';
else
cout << '-';
}
cout << endl;
}
cout << endl;
}
void update()
{
int new_grid[20 + 2][60 + 2];
for (int row = 1; row <= 20; row++)
{
for (int col = 1; col <= 60; col++)
{
int count_result = neighbor_count(row, col);
if (count_result == 2)
new_grid[row][col] = grid[row][col];
else if (count_result == 3)
new_grid[row][col] = 1;
else
new_grid[row][col] = 0;
}
}
for (int row = 1; row <= 20; row++)
{
for (int col = 1; col <= 60; col++)
{
grid[row][col] = new_grid[row][col];
}
}
}
private:
int grid[20 + 2][60 + 2]; //sentinel
int neighbor_count(int row, int col)
{
int count = 0;
for (int i = row - 1; i <= row + 1; i++)
{
for (int j = col - 1; j <= col + 1; j++)
{
count += grid[i][j];
}
}
count -= grid[row][col];
return count;
}
};
int main()
{
Life consruction;
consruction.initialize();
int n;
cin >> n;
while (n--)
{
consruction.update();
}
consruction.print();
return 0;
}