输出为:1 2 3
8 9 4
7 6 5
n=4时 数组为{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
输出为:1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
问如何编写此程序?
用一维数组的话
#include <iostream>
#include<iomanip>
using namespace std;
int main(){
cout<<"input n: ";
int n;
while(!(cin>>n))
{
cout<<"input error\n";
cin.clear();
while(cin.get()!='\n'){}
cout<<"input n : ";
}
int *p=new int[n];
double half=(n-1)/2;
int circle=0;
for(int line=0; line<n; line++)
{
for(int list=0; list<n; list++)
{
int tmp1=(line > half ? n-line-1: line);
int tmp2=(list > half ? n-list-1: list);
circle=(tmp1 < tmp2 ? tmp1 : tmp2);
int circler_total=0;
int tempN=n;
if(list >= line)
{
for(int i=0; i<circle; i++)
{
circler_total+=4*(tempN-1);
tempN-=2;
}
p
}
delete[]p;
system("pause");
}
/*
把矩阵分成几个框
1 2 3 4 1 2 3 4
12 13 14 5 => 12 5 和 13 14
11 16 15 6 11 6 16 15
10 9 8 7 10 9 8 7
方法可能比较笨,但是应该还算直观...
*/
#include <iostream.h>
int CalcStartVal( int startPos, int n ) //计算每个框的初始值(左上角)
{
int startVal = 1;
for ( int i = 0; i < startPos; i++ ){
startVal += ( n + ( n - 2 ) + n + ( n - 2 ) );
n -= 2;
}
return startVal;
}
int CalcStartPosNum( int n ) //计算框数
{
return n / 2 + n % 2;
}
//填充框的上边
void FillTop( int startPos, int startVal, int **theFrame, int n )
{
int end = n - 2 * startPos;
for ( int i =0; i < end; i++ )
theFrame[ startPos ][ startPos + i ] = startVal + i;
}
//填充框的右边
void Fillright( int startPos, int startVal, int **theFrame, int n )
{
int end = n - 2 * startPos - 2;
for ( int i = 0; i < end; i++ )
theFrame[ startPos + i + 1 ][ startPos + end + 1 ]
= startVal + ( end + 2 ) + i;
}
//填充框的下边
void FillBottom( int startPos, int startVal, int **theFrame, int n )
{
int end = n - 2 * startPos;
for ( int i = 0 ; i < end; i++ ){
theFrame[ startPos + end - 1 ][ startPos + end -1 - i ]
= startVal + 2 * end - 2 + i;
}
}
//填充框的左边
void FillLeft( int startPos, int startVal, int **theFrame, int n )
{
int end = n - 2 * startPos - 2;
for ( int i = 0; i < end; i++ )
theFrame[ startPos + end - i ][ startPos ]
= startVal + 3 * ( end + 2 ) -2 + i;
}
//填充一个框
void FillFrame( int startPos, int n, int **theFrame )
{
int startVal = CalcStartVal( startPos, n );
FillTop( startPos, startVal, theFrame, n );
Fillright( startPos, startVal, theFrame, n );
FillBottom( startPos, startVal, theFrame, n );
FillLeft( startPos, startVal, theFrame,n );
}
void main()
{
int n;
cout << "输入N值:" << endl;
cin >> n;
int **matrix = new int*[n];
for ( int i2 = 0; i2 < n; i2++ )
matrix[i2] =new int[n]; //根据输入分配矩阵存储
for ( int i1 = 0; i1 < CalcStartPosNum( n ); i1++ )
FillFrame( i1, n, matrix ); //填充数值
cout << endl ; //显示结果
for ( int i = 0; i < n; i++ ){
for ( int j = 0; j < n; j++ ){
cout << matrix[ i ][ j ];
if ( i == 0 )
cout << " ";
else
cout << " ";
}
cout << endl << endl;
}
for ( i2 = 0; i2 < n; i2++ )
delete [] matrix[i2];
delete [] matrix; //删除指针
}
//O(n^2);没有作输入检查...