#include <iostream> #include <cstdlib> #include <algorithm> using namespace std; const int N = 100; int data[N + 1][N + 1]; enum DIRECTION { RIGHT, DOWN , LEFT, UP }; int max(int a,int b) { return (a>b?a:b); } //模拟整个过程 void Simulate(int n) { int x, y; x = y = (n - 1) / 2; //1的位置 data[x][y] = 1; int len = 1; int count = 0; int num = 2; DIRECTION dir = RIGHT; while(num <= n * n) { for(int i = 0; i < len; i++) { switch(dir) { case LEFT: --y; break; case RIGHT: ++y; break; case UP: --x; break; case DOWN: ++x; break; default: break; } data[x][y] = num++; } count++; if(count == 2) { count = 0; len++; } dir = (DIRECTION)((dir + 1) % 4); } } //打印螺旋矩阵 void Output(int n) { int i, j; for(i = 0; i < n; i++) { cout << data[i][0]; for(j = 1; j < n; j++) cout << "/t" << data[i][j]; cout << endl; } } //以(1,1)所在位置作为原点,向右作为x正半轴,向下作为y正半轴 int GetValue(int x, int y) { int m = max(abs(x), abs(y)); int rightBottom = m * m * 4 - 2 * m + 1; int value = 0; if(x == -m) { value = rightBottom + 2 * m + m - y; } else if( y == m) { value = rightBottom + m - x; } else if(y == -m) { value = rightBottom + 4 * m + x + m; } else if( x == m ) { value = rightBottom - (m - y); } return value; } void TestPos(int n) { int i, j; for(i = 0; i < n; i++) { cout << GetValue(0 - (n - 1) / 2, i - (n - 1) / 2); for(j = 1; j < n; j++) cout << "/t" << GetValue(j - (n - 1) / 2, i - (n - 1) / 2); cout << endl; } } int main() { int n; while(cin >> n) { if(n <= 0 || n > 100) { cerr << "Size error!" << endl; break; } else { Simulate(n); Output(n); cout << "*******************" << endl; TestPos(n); } } return 0; }