题目:给你一个整数n 按要求输出n*n的回型矩阵。
1<= n<=19
示例1:
输入:4
输出:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
c++
#include<iostream>
using namespace std;
const int N = 20;
int a[N][N];
int main() {
int n, index = 1;
cin >> n;
int lx = 1, ly = 1, hx = n, hy = n;
while (index <= n * n) {
//向右走
for (int i = ly; i <= hy; i++) a[lx][i] = index++; lx++;
//向下走
for (int i = lx; i <= hx; i++) a[i][hy] = index++; hy--;
//向左走
for (int i = hy; i >= ly; i--) a[hx][i] = index++; hx--;
//向上走
for (int i = hx; i >= lx; i--) a[i][ly] = index++; ly++;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << a[i][j] << " ";
}
cout << endl;
}
return 0;
}
代码在我的编译器上的运行结果: