You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

24 lines
569 B

#include<bits/stdc++.h>
using namespace std;
int a[10][10];
int main() {
int i, j, n, count;
memset(a, 0, sizeof(a));
scanf("%d", &n);
count = a[i = 1][j = n] = 1;//赋初值,方向为:右->左
while(count < n*n) {
while(i<n && !a[i+1][j]) a[++i][j] = ++count;//下
while(j>1 && !a[i][j-1]) a[i][--j] = ++count;//左
while(i>1 && !a[i-1][j]) a[--i][j] = ++count;//上
while(j<n && !a[i][j+1]) a[i][++j] = ++count;//右
}
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++) {
if(j == n) printf("%3d\n", a[i][j]);
else printf("%3d", a[i][j]);
}
return 0;
}