life.h

来自「这是本人精心搜集的关于常用图论算法的一套源码」· C头文件 代码 · 共 86 行

H
86
字号
const int maxrow = 20, maxcol = 60;    // grid dimensions

class Life 
 { 
  public:
    void initialize( );
    void print( );
    void update( );
  private:
     int grid[maxrow+2][maxcol+2];
      // allows for two extra rows and columns
     int neighbor_count(int row, int col);
};

int Life::neighbor_count(int row, int col)
/* Pre: The Life object contains a conguration, and the coordinates row and col
         define a cell inside its hedge.
   Post: The number of living neighbors of the specied cell is returned. */
{  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]; // Increase the count if neighbor is alive.
   count -= grid[row][col];
      // Reduce count, since cell is not its own neighbor.
   return count;
}

void Life::update( )
/* Pre: TheLife object contains a configuration.
   Post: TheLife object contains the next generation of configuration. */
{ int row, col;
  int new_grid[maxrow+2][maxcol+2];
  for(row=1; row<=maxrow; row++)
     for(col=1; col<=maxcol; col++)
     switch (neighbor_count(row,col)) 
      {
        case 2:
           new_grid[row][col]=grid[row][col];
             // Status stays the same.
           break;
        case 3:
           new_grid[row][col]=1; // Cell is now alive.
           break;
        default:
           new_grid[row][col]=0; // Cell is now dead.
      }
  for(row=1; row<=maxrow; row++)
  for(col=1; col<=maxcol; col++)
  grid[row][col] = new_grid[row][col];
} 

void Life::print( )
/* Pre: TheLife object contains a conguration.
   Post: The conguration is written for the user. */
{ int row, col;
  cout<<"\nThe current Life configuration is:\n";
  for(row = 1; row <= maxrow; row++)
   {
     for(col = 1; col <= maxcol; col++)
         if(grid[row][col]==1) cout<<'*';
          else cout<<' ';
     cout<<endl;
   }
}

void Life::initialize( )
/* Pre: None.
   Post: TheLife object contains a conguration specied by the user. */
{ int row, col;
  for(row=0; row<=maxrow+1; row++)
     for(col=0; col<=maxcol+1; col++)
         grid[row][col] = 0;
  cout<<"List the coordinates for living cells." << endl;
  cout<<"Terminate the list with the the special pair -1 -1" << endl;
  cin>>row>>col; 
  while(row!= -1||col!=-1)
   { if(row>=1 && row<=maxrow)
       if(col>=1 && col<=maxcol)
          grid[row][col]=1;
        else
          cout<<"Column "<<col<<" is out of range.\n";
     else
          cout<<"Row "<<row<<" is out of range.\n";
     cin>>row>>col;
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?