打印螺旋数字矩阵

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;
}

posted @ 2012-11-08 17:05  byfei  阅读(267)  评论(0编辑  收藏  举报