构造螺旋矩阵

题目:输入一组数字,按照从小到大构造成螺旋矩阵并输出。

<pre name="code" class="cpp">#include <iostream>
using namespace std;
const int M=5;
const int N=4;

int index=0;

//快速排序之划分算法
int Partition(int a[],int low,int high)
{
	int pivot=a[low];
	while(low<high)
	{
		while(low<high && a[high]>=pivot)
			high--;
		a[low]=a[high];
		while(low<high && a[low]<=pivot)
			low++;
		a[high]=a[low];
	}
	a[low]=pivot;
	return low;
}

//快排递归调用
void QuickSort(int a[],int low,int high)
{
	int pivotpos;
	if(low<high)
	{
		pivotpos=Partition(a,low,high);
		QuickSort(a,low,pivotpos-1);
		QuickSort(a,pivotpos+1,high);
	}
}


void SetRollMatrix(int number[][N],int row,int col,int start,int a[])
{
	int endX=col-1-start;
	int endY=row-1-start;

	//从左往右设置一行
	for(int i=start;i<=endX;i++)
	{
		number[start][i]=a[index++];
	}

	//从上到下设置一列
	if(start<endY)
	{
		for(int i=start+1;i<=endY;++i)
			number[i][endX]=a[index++];
	}

	//从右到左设置一行
	if(start<endX && start<endY)
	{
		for(int i= endX-1;i>=start;--i)
			number[endY][i]=a[index++];
	}

	//从下到上打印一列
	if(start<endX && start <endY-1)
	{
		for(int i=endY-1;i>=start+1;--i)
			number[i][start]=a[index++];
	}
		
}

void PrintRollMatrix(int number[][N],int row,int col,int a[])
{
	if(number==NULL || row<=0 || col<=0)
		return;
	int start=0;
	while(row>start*2 && col>=start*2)
	{
		SetRollMatrix(number,row,col,start,a);
		start++;
	}
}

int main()
{
	int a[M*N]={3,6,15,7,16,9,11,17,14,13,18,1,2,5,4,8,10,19,12,20};
	QuickSort(a,0,M*N-1);

	for(int i=0;i<M*N;i++)
		cout<<a[i]<<' ';
	cout<<endl<<endl;

	int matrix[M][N];
	PrintRollMatrix(matrix,M,N,a);

	for(int i=0;i<M;i++)
	{
		for(int j=0;j<N;j++)
			cout<<matrix[i][j]<<' ';
		cout<<endl;
	}
	
	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值