/*
 Magic Array
*/
#include<iostream>
#include<iomanip>

using namespace std;

#define size 5
#define start 0

struct Node
{
 int value;
};

void Init(Node array[size][size])
{
 for(int i=start;i<size;i++)
 {
  for(int j=start;j<size;j++)
  {
   array[i][j].value = 0;
  }
 }
}

void Check(int x,int y,int &nextx,int &nexty,Node array[size][size])
{
 if( array[nextx][nexty].value != 0 )
 {
  nextx = x+1;
  if( nextx > size-1 )
   nextx = 0;
  nexty = y;
 } 

}

void Magic(Node array[size][size])
{
 int x = start,y = size/2,nextx,nexty;

 array[x][y].value = 1;
 nextx = x;
 nexty = y;

 for(int i=2;i<=size*size;i++)
 {
  nextx--;
  nexty--;

  if( nextx < 0 )
  {
   nextx = size-1;
   if( nexty < 0 )
    nexty = size-1;
   Check(x,y,nextx,nexty,array);
   array[nextx][nexty].value = i;
  }
  else if( nexty < 0 )
  {
   nexty = size-1;
   Check(x,y,nextx,nexty,array);
   array[nextx][nexty].value = i; 
  }

  else
  {
   Check(x,y,nextx,nexty,array);
   array[nextx][nexty].value = i;
  }

  x = nextx;
  y = nexty;

 }


}

void Print(Node array[size][size])
{
 for(int i=start;i<size;i++)
 {
  cout<<"---------------------------"<<endl;
  cout<<"| ";
  for(int j=start;j<size;j++)
  {
   cout<<setiosflags(ios::right)<<setw(3)<<array[i][j].value<<" |";
  }
  cout<<endl;
 }
 cout<<"---------------------------"<<endl;

}

int main()
{
 Node array[size][size];

 Init(array);
 Magic(array);
 Print(array);

 return 0;
}


執行結果:

 

魔術方陣規則:

1. 將第一列的中間填入1
2. 以1的級數增加並填入左上角
3. 若超出陣列上方,則填入最下面一列之對應位置;
    若超出陣列左方,則填入最右一列之對應位置
4. 假如欲填入的方格以填滿,則在原地下面一格填入數值
5. 重複第二步驟以下的動作 

文章標籤
全站熱搜
創作者介紹
創作者 flyinsky76 的頭像
flyinsky76

Deja Vu

flyinsky76 發表在 痞客邦 留言(0) 人氣(289)