输入两个数,第一个数决定一个nXn的矩阵,第二个数决定从1开始赋值,赋值的上限
比如:
输入:5 18
输出:p q
1 2 3 4 5
16 17 18 0 6
15 0 0 0 7
14 0 0 0 8
13 12 11 10 9
#include <stdio.h>
#define RIGHT 1
#define DOWN 2
#define LEFT 3
#define UP 4
int main(int argc, const char * argv[]) {
int a[20][20]={};
int n, m;
scanf("%d%d", &n,&m);
if (n<1||m<1||m>n*n||n>20) {
return -1;
}
int type=RIGHT;//1:从左往右赋值 2:从上往下赋值 3:从右往左赋值4:从下往上赋值
int p=0,q=0;
int s1=n-1;
int s2=n-1;
int s3=0;
int s4=1;
int i=1;
while (i<=m) {
a[p][q]=i;
switch (type) {
case RIGHT:
if (++q==s1) {//判断是否到边界
type = DOWN;
s1--;
}
break;
case DOWN:
if (++p==s2) {
type = LEFT;
s2--;
}
break;
case LEFT:
if (--q==s3) {
type = UP;
s3++;
}
break;
case UP:
if (--p==s4) {
type=RIGHT;
s4++;
}
break;
default:
break;
}
i++;
}
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
printf("%4d", a[i][j]);
}
printf("\n");
}
return 0;
}