螺旋矩阵(由外自内旋转)

22 篇文章 0 订阅
15 篇文章 1 订阅

如矩阵:


找出规律,并打印出一个N*N的矩阵;规律就是从首坐标开始顺时针一次增大。(题目出自程序员面试宝典第三版)

注:由于觉得书上的程序比较的复杂因此使用自己的方法。

//_OUTSIDESPIN.H_
#ifndef OUTSIDESPIN_H
#define OUTSIDESPIN_H
class OutsideSpin
{
public:
	OutsideSpin();
	OutsideSpin(int);
	void print();
	void print(int);
	~OutsideSpin();
private:
	int n;
	int **out;
};
#endif//_OUTSIDESPIN.H_
//OutsideSpin.cpp
#include<iostream>
#include"OutsideSpin.h"
using namespace std;

OutsideSpin::OutsideSpin(){}
OutsideSpin::OutsideSpin(int n):n(n)
{
	out = new int *[n];
	for(int i=0;i<n;i++)
	{
		out[i] = new int[n];
	}
	int total = 1;
	int x=0,y=0;
	int start=0, end =n;
	while(n>0)
	{
		for(int i = start;i<end-1;i++)
		{
			out[x][y++]=total++;
		}
		for(int i =start;i<end-1;i++)
		{
			out[x++][y]=total++;
		}
		for(int i = start;i<end-1;i++)
		{
			out[x][y--]=total++;
		}
		for(int i = start;i<end-1;i++)
		{
			out[x--][y]=total++;
		}
		if(start==end-1)
		{
			out[x][y]=total;
		}
		start++,x++,y++;
		end--;
		n = n-2;
	}
}
OutsideSpin::~OutsideSpin()
{
	for(int i=0;i<n;i++)
	{
		delete[] out[i];
	}
	delete[] out;
}
void OutsideSpin::print(int n0)
{
	cout<<"***********************结果如下****************************"<<endl;
	for(int i =0;i<n0;i++)
	{
		for(int j=0;j<n0;j++)
			cout<<out[i][j]<<"	";
		cout<<endl;
	}
	cout<<"************************************************************"<<endl;
}

void OutsideSpin::print()
{
	print(n);
}
//OutsideSpinMain.cpp
#include<iostream>
#include"OutsideSpin.h"
using namespace std;
int main()
{
	do
	{
		cout<<"输入矩阵的维数n:"<<endl;
		int n ;
		cin>>n;
		OutsideSpin o(n);
		o.print();
	}while(!std::cin.eof());
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值