题目描述
给你一个整数n,按要求输出n∗n的回型矩阵
输入格式输入一行,包含一个整数n
1<=n<=19
输出格式输出n行,每行包含n个正整数.
样例样例输入
4
样例输出
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
数据范围与提示
分类标签
[二维数组]
C++题解代码
#include <bits/stdc++.h>
using namespace std;
int a[20][20];
int b;
int c;
int d;
int e;
int f;
void fn(int x, int y, int z) {
for (int i = 1; i < z; i++) {
a[x][y] = c;
y++;
c++;
}
for (int i = 1; i < z; i++) {
a[x][y] = c;
x++;
c++;
}
for (int i = 1; i < z; i++) {
a[x][y] = c;
y--;
c++;
}
for (int i = 1; i < z; i++) {
a[x][y] = c;
x--;
c++;
}
}
int main() {
cin>>b;
c = 1;
d = b;
e = 1;
f = 1;
while (d > 1) {
fn(e, f, d);
d -= 2;
e++;
f++;
}
if (d == 1) {
a[e][f] = c;
}
for (int i = 1; i <= b; i++) {
for (int j = 1; j <= b; j++) {
cout<<a[i][j];
if (j != b) {
cout<<" ";
}
}
if (i != b) {
cout<<'\n';
}
}
return 0;
}
Blockly题解代码图片