Compiler:VC++
複製程式
#if 0
1.假設以左下角為原點。
2.X軸向右為正。
3.Y軸向上為正。
#endif
#include <iostream>
using namespace std;
const int DX[4] = {0, -1, 0, 1};
const int DY[4] = {1, 0, -1, 0};
class CIntMartix
{
private:
int m_N;
int **m_ptr;
public:
CIntMartix(int N)
{
m_N = N;
m_ptr = new int *[m_N];
for(int i = 0; i < m_N; i++)
{
m_ptr[i] = new int[m_N];
for(int j = 0; j < N; j++)
m_ptr[i][j] = 0;
}
}
~CIntMartix()
{
for(int i = 0; i < m_N; i++)
delete [] m_ptr[i];
}
void Display(void)
{
int x, y;
for(y = m_N - 1; y >= 0; y--)
{
for(x = 0; x < m_N; x++)
cout << m_ptr[x][y] << "\t";
cout << endl;
}
}
int & Get(int x, int y)
{
return m_ptr[x][y];
}
};
int main(void)
{
int N;
cout << "Please input N:";
cin >> N;
if (N < 2 || N > 10)
{
cout << "N must be between 2 to 10." << endl;
return 1;
}
CIntMartix MyMatrix(N);
int iCounter = 1;
int x = N - 1;
int y = 0;
int dir = 0;
//Initial the first point.
MyMatrix.Get(x, y) = 1;
iCounter++;
while(iCounter <= N * N)
{
int x1 = x + DX[dir];
int y1 = y + DY[dir];
if(x1 >= 0 && y1 < N &&
y1 >= 0 && y1 < N &&
MyMatrix.Get(x1, y1) == 0)
{
x = x1;
y = y1;
MyMatrix.Get(x, y) = iCounter;
iCounter++;
}
else
{ //Turn to next direction.
dir++;
if(dir == 4)
dir = 0;
}
}
MyMatrix.Display();
//system("pause");
return 0;
}