螺旋矩阵
原题如下:
打印出参数为N的矩阵,比如输入3,则打印出
1 2 3
8 9 4
7 6 5
输入4
打印出
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
下面是我的答案
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
void PrintArray(int* arr, int len)
{
int i,j = 0;
for( i = 0; i < len; i++)
{
for( j = 0; j < len; j++ )
{
cout << setw(6) << arr[i * len + j];
}
cout << "\n";
}
}
int main()
{
enum Director
{
right,
bottom,
left,
top
};
int i = 0;
cin >> i;
if (i <= 0)
{
return 0;
}
Director director = right;
int * martix = new int[i*i];
int x = 0, y = 0;
int num = 1;
int round = 0;
while(num < i * i)
{
cout<< "x=" << x << " y="<< y << " value = " << num<< endl;
switch(director)
{
case right:
//如果右边超过边界
if (x + 2 > i - round)
{
director = bottom;
}
else
{
martix[y * i + x] = num++;
x++;
}
break;
case bottom:
if (y + 2 > i - round)
{
director = left;
}
else
{
martix[y * i + x] = num++;
y++;
}
break;
case left:
if (x < round + 1)
{
director = top;
}
else
{
martix[y * i + x] = num++;
x--;
}
break;
case top:
if (y <= round + 1)
{
//重新开始一轮
round ++;
director = right;
}
else
{
martix[y * i + x] = num++;
y--;
}
break;
}
}
martix[y * i + x] = num++;
PrintArray(martix, i);
system("pause");
delete[] martix;
return 1;
}
#include <iostream>
#include <iomanip>
using namespace std;
void PrintArray(int* arr, int len)
{
int i,j = 0;
for( i = 0; i < len; i++)
{
for( j = 0; j < len; j++ )
{
cout << setw(6) << arr[i * len + j];
}
cout << "\n";
}
}
int main()
{
enum Director
{
right,
bottom,
left,
top
};
int i = 0;
cin >> i;
if (i <= 0)
{
return 0;
}
Director director = right;
int * martix = new int[i*i];
int x = 0, y = 0;
int num = 1;
int round = 0;
while(num < i * i)
{
cout<< "x=" << x << " y="<< y << " value = " << num<< endl;
switch(director)
{
case right:
//如果右边超过边界
if (x + 2 > i - round)
{
director = bottom;
}
else
{
martix[y * i + x] = num++;
x++;
}
break;
case bottom:
if (y + 2 > i - round)
{
director = left;
}
else
{
martix[y * i + x] = num++;
y++;
}
break;
case left:
if (x < round + 1)
{
director = top;
}
else
{
martix[y * i + x] = num++;
x--;
}
break;
case top:
if (y <= round + 1)
{
//重新开始一轮
round ++;
director = right;
}
else
{
martix[y * i + x] = num++;
y--;
}
break;
}
}
martix[y * i + x] = num++;
PrintArray(martix, i);
system("pause");
delete[] martix;
return 1;
}