螺旋矩阵

976 词

题目描述

给定一个正整数n$(1<=n<=20)$,画出螺旋矩阵。

输入

一个正整数n

输出

对应画出螺旋矩阵

样例输入

1
5

样例输出

1
2
3
4
5
1 2 3 4 5 
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

提示

每一个数后输出空格

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;
int a[21][21];
int n;
int main() {
cin >> n;
int x = 0, y = 0;
a[x][y] = 1;
for (int k = 2; k <= n * n; ) {
while (true) {
int nx = x, ny = y + 1;
if (nx < 0 nx >= n ny < 0 ny >= n a[nx][ny]) {
break;
}
a[x = nx][y = ny] = k++;
}
while (true) {
int nx = x + 1, ny = y;
if (nx < 0 nx >= n ny < 0 ny >= n a[nx][ny]) {
break;
}
a[x = nx][y = ny] = k++;
}
while (true) {
int nx = x, ny = y - 1;
if (nx < 0 nx >= n ny < 0 ny >= n a[nx][ny]) {
break;
}
a[x = nx][y = ny] = k++;
}
while (true) {
int nx = x - 1, ny = y;
if (nx < 0 nx >= n ny < 0 ny >= n a[nx][ny]) {
break;
}
a[x = nx][y = ny] = k++;
}
}
for (int ii = 0; ii < n; ii++) {
for (int jj = 0; jj < n; jj++) {
cout << a[ii][jj] << " ";
}
cout << endl;
}
return 0;
}