狄泰软件课堂笔记
#include <iostream>
/* 旋转数组的打印,逆时针增大 */
using namespace std;
#define N 5
class Spin_Matrix
{
private:
int Matrix[N][N];
struct pos
{
int dx;
int dy;
};
bool valid(int x, int y)
{
bool ret = true;
ret = ret && (x < N );
ret = ret && (x < N );
ret = ret && (Matrix[x][y] == 0);
return ret;
}
public:
Spin_Matrix()
{
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
Matrix[i][j] = 0 ;
}
}
}
void run()
{
const pos cd[4] ={{1,0}, {0,1}, {-1,0}, {0,-1}}; // 顺时针 {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
int cx = 0;
int cy = 0;
int j = 1;
int k = 0;
do
{
Matrix[cx][cy] = j;
if( !valid(cx + cd[k].dx , cy + cd[k].dy) )
{
k++;
k = k%4;
}
cx += cd[k].dx;
cy += cd[k].dy;
j++;
}while(j <= N*N);
}
void print()
{
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
cout << Matrix[i][j] << " " ;
}
cout << endl;
}
cout << endl;
}
};
int main()
{
Spin_Matrix matrix;
matrix.run();
matrix.print();
return 0;
}