# 打印螺旋数

1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

3
4

1 2 3
8 9 4
7 6 5

1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

1 #include <iostream>
2
3 using namespace std;
4
5 int matrix[21][21];
6
7 int main()
8 {
9 	int n;
10 	while (cin >> n)
11 	{
12 		int sx = 0, sy = 0, ex = n - 1, ey = n - 1;
13 		int idx = 0;
14
15 		while (true)
16 		{
17 			//横着从左到右
18 			for (int i = sy; i <= ey; ++i)
19 			{
20 				matrix[sx][i] = ++idx;
21 			}
22 			++sx;
23 			if (sx > ex)break;
24
25 			//竖着从上到下
26 			for (int i = sx; i <= ex; ++i)
27 			{
28 				matrix[i][ey] = ++idx;
29 			}
30 			--ey;
31 			if (sy > ey)break;
32
33 			//横着从右向左
34 			for (int i = ey; i >= sy; --i)
35 			{
36 				matrix[ex][i] = ++idx;
37 			}
38 			--ex;
39 			if (sx > ex)break;
40
41 			//竖着从下到上
42 			for (int i = ex; i >= sx; --i)
43 			{
44 				matrix[i][sy] = ++idx;
45 			}
46 			++sy;
47 			if (sy > ey)break;
48 		}
49
50 		for (int i = 0; i < n; ++i)
51 		{
52 			for (int j = 0; j < n; ++j)
53 			{
54 				cout << matrix[i][j];
55 				if (j != n - 1)cout << " ";
56 			}
57 			cout << endl;
58 		}
59 		cout << endl;
60 	}
61 	return 0;
62 }