加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

一个螺旋矩阵的C语言代码

(2011-10-26 21:25:05)
标签:

it

分类: 玩弄学究
原题目链接:
http://www.hack95.com/read.php?tid-108899-fpage-4-displayMode-1-page-1.html
题目描述:
从键盘输入一个整数(1~20
则以该数字为矩阵的大小,把1,2,3…n*n 的数字按照顺时针螺旋的形式填入其中。例如:
输入数字2,则程序输出:
1 2
4 3
输入数字3,则程序输出:
1 2 3
8 9 4
7 6 5
输入数字4, 则程序输出:
    4
12  13  14  5
11  16  15  6
10     7
看题理解,15min;编程调试运行,45min:共1hour,是不是太慢了,好久都没编程做数学题了!!!
代码如下:
//spiral_matrix.cpp
//////////////////////////////////////////////
#include <stdio.h>
#define N 25

int main()
{
while(1)
{
int length,i,num=1,row=0,col=0;
int matrix[N+1][N+1]={0};
printf("Please input a number in 1-%d: ",N);
scanf("%d",&length);
int max=length*length;
for(i=0;i<length/2;i++)
{
for (;length-1-i>col;col++)
matrix[row][col]=num++;
for (;length-1-i>row;row++)
matrix[row][col]=num++;
for (;col>i;col--)
matrix[row][col]=num++;
for (;row>i;row--)
matrix[row][col]=num++;
row++;col++;
}
if(length%2==1)
matrix[row][col]=num++;
for(row=0;row<length;row++)
{
for(col=0;col<length;col++)
printf(format,matrix[row][col]); //3d!
printf("\n");
}
}
return 0;
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有