1. 程式人生 > >列印螺旋數字矩陣

列印螺旋數字矩陣

1:如下,是一個“4×4”的數字矩陣,請找出其中的規律,然後編寫一個程式,要求能打印出“N×N”時的數字矩陣:
 1     2      3    4
12   13   14   5
11   16   15   6
10     9     8    7
請用自己最熟悉的語言編寫,或者用自然語言描述。至少要包括下列內容:
1: 數字矩陣的規律
2: 採用的資料結構
3:關鍵的控制流程

 #include<iostream>
 #include<cmath>
 #define N 4
 using namespace std;
 int main()
 {
     int i,j;
     int count=0;
     int a[N][N];
     for(i=0;i<N/2;i++)
     {
         for(j=i;j<N-i-1;j++)
             a[i][j]=++count;
         for(j=i;j<N-i-1;j++)
             a[j][N-i-1]=++count;
         for(j=i;j<N-i-1;j++)
             a[N-i-1][N-1-j]=++count;
         for(j=i;j<N-i-1;j++)
             a[N-1-j][i]=++count;
     }
     if(N%2!=0)
         a[N/2][N/2]=++count;
     for(i=0;i<N;i++)
     {
         for(j=0;j<N;j++)
             cout<<a[i][j]<<ends;
         cout<<endl;
     }
     return 0;
 }


下面這個是自己寫的

#include<iostream>
#include <map>
const int N = 10;
const int MaxMap = 100;
using namespace std;

enum
{
   Right = 0,
   Dowm = 1,
   Left = 2,
   Up = 3
};

int GetValue(int x,int y)
{
	int nValue = x+y*MaxMap;
	return nValue;
}

void Move(int Num,int &x,int &y)
{
	switch (Num%4) 
	{
	case Right: 
		x++;
		break;
	case Dowm:
		y++;
		break;
	case Left:
		x--;
		break;
	case Up:
		y--;
		break;
	}
}

void FillMap(map <int,int> &MapPonit)
{
	int Now_x=1,Now_y=1;    //當前座標
	int Next_x=1,Next_y =1; //下一步的座標
	int Num = 0;

	for(int i=1;i<=N*N;i++)
	{
		// 轉彎有二種情況,1.下一個點已經走過,2.一個方向上走到最大值N
		if(((i-1)%(N-1)==0&&Num<3&&2<i))
			Num++;
		if(MapPonit.find(GetValue(Next_x,Next_y)) == MapPonit.end())
		{
			Now_x = Next_x;
			Now_y = Next_y;
		}
		else
		{	 
			Num++;
			Move(Num,Now_x,Now_y);
			Next_x = Now_x;
			Next_y = Now_y;
		}
		//根據value值儲存所有走過的點
		Move(Num,Next_x,Next_y);
		MapPonit[GetValue(Now_x,Now_y)] = i;
	}
}

void Print(map <int,int> MapPonit)
{
	map <int,int>::iterator itr = MapPonit.begin();
	int NCout = 0;
	for(itr;itr!=MapPonit.end();itr++)
	{
		if(NCout%N == 0)
			cout<<endl;
		int nStep = itr->second;
		if(nStep<10)
			cout<<0;
		cout<<nStep<<" ";
		NCout++;
	}
}

int main()
{
	map <int,int> MapPonit;
	FillMap(MapPonit);
	Print(MapPonit);
	getchar();
	return 0;
}