2 回答
TA贡献1797条经验 获得超6个赞
// It is so easy. Just use five FOR sentences with high efficiency and simplest.
void fun(int **p, unsigned char n) // create a screw matrix with n
{ // return by pointer p
unsigned char k, i, l = (n+1)/2;
int c = 1;
p[l-1][l-1] = n * n;
for(k=0; k<l; k++, n-=2)
{
for(i=0;i<n-1;i++) p[k][k+i]=c++;
for(i=0;i<n-1;i++) p[k+i][k+n-1]=c++;
for(i=n-1;i>0;i--) p[k+n-1][k+i]=c++;
for(i=n-1;i>0;i--) p[k+i][k]=c++;
}
} // end of fun
// You can write a main function to test it, which is so simple even without using one IF sentence.
TA贡献1794条经验 获得超8个赞
#include <stdio.h>
//Up,Down,Left,Right
#define U 'U'
#define D 'D'
#define L 'L'
#define R 'R'
const int MAX = 10;
int main(int argc, char *argv[]){
int matrix[MAX][MAX];
int n, x, y, k;
char direction; //Up,Down,Left,Right
// get input
printf("Please input n(n<%d): ", MAX+1);
scanf("%d", &n);
// invalid input
if(n>MAX || n<1) return -1;
// initializations
for (y=0;y<n;y++)
for (x=0;x<n;x++)
matrix[x][y]=0;
for (y=n;y<MAX;y++)
for (x=n;x<MAX;x++)
matrix[x][y]=-1;
x=y=k=0;
direction = R;
// build the matrix
while(1){
if (matrix[x][y]==0){
matrix[x][y]=++k;
switch (direction){
case U:y--;break;
case D:y++;break;
case L:x--;break;
case R:x++;break;
default:break;
}
}else{
switch (direction){
case U:direction=R;y++;x++;break;
case D:direction=L;y--;x--;break;
case L:direction=U;y--;x++;break;
case R:direction=D;y++;x--;break;
default:break;
}
}
// finished
if (k==n*n) break;
}
// output
for (y=0;y<n;y++){
for (x=0;x<n;x++)
printf("%3d", matrix[x][y]);
printf("\n");
}
// exit with no error
return 0;
}
-----------------------------------------------------
- 2 回答
- 0 关注
- 270 浏览
添加回答
举报