|
发表于 2009-11-2 01:23:32
|
显示全部楼层
IP:江苏扬州
/*
把矩阵分成几个框
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);没有作输入检查... |
|