题目描述
给定一个正整数n(1<=n<=20),画出螺旋矩阵。
输入
一个正整数n
输出
对应画出螺旋矩阵
#include<bits/stdc++.h>
using namespace std;
const int maxn = 21;
int a[maxn][maxn];
int n;
void show() {
for (int x = 0; x < n; x++) {
for (int y = 0; y < n; y++) {
cout << a[x][y] << “ “;
}
cout << endl;
}
}
void cal() {
int x = 0, y = 0;
a[x][y] = 1;
for (int k = 2; k <= n * n; ) {
while (1) {
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 (1) {
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 (1) {
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 (1) {
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++;
}
}
}
int main() {
cin >> n;
cal();
show();
return 0;
}