3
7 8 9
6 1 2
5 4 3
4
7 8 9 10
6 1 2 11
5 4 3 12
16 15 14 13
5
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
直接给出三组数据,第一行代表矩形的大小,然后输出 接下来的 数圈,题目就是这样。
直接采用暴力解法,每写一步都要注意边界条件,以及循环的结束条件:
my code:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int n,num,x,y;
cin >> n;
int a[n][n];
memset(a,0,sizeof(a));
num = a[x = n-1][y = 0] = n*n;
while(num > 1) {
while(y+1<n && !a[x][y+1]) a[x][++y] = --num;
while(x-1>=0 && !a[x-1][y]) a[--x][y] = --num;
while(y-1>=0 && !a[x][y-1]) a[x][--y] = --num;
while(x+1<n && !a[x+1][y]) a[++x][y] = --num;
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
x = n%2 == 0 ? i : n - i - 1;
y = n%2 == 0 ? j : n - j - 1;
cout << a[x][y] << " ";
}
if(i != n-1)cout<<endl;
}
return 0;
}