首页 > 其他 > 详细

写个简单的螺旋打印矩阵程序-C

时间:2015-04-13 18:39:20      阅读:218      评论:0      收藏:0      [点我收藏+]
#include<stdio.h>
#define PRINT(x) printf("%03d ",(x))
void spiral_matrix_print(const int matrix[][4],int rows,int columns)
{
	int top,left,i;
	int bottom = rows-1;
	int right = columns-1;
	top = left = i =0;
	while(bottom>=top && right>=left)
	{
		for(i=left;i<=right;i++)//top
			PRINT(matrix[top][i]);
		if(++top>bottom) break;

		for(i=top;i<=bottom;i++)//right
			PRINT(matrix[i][right]);
		if(--right<left) break;

		for(i=right;i>=left;i--)//bottom
			PRINT(matrix[bottom][i]);
		if(--bottom<top) break;

		for(i=bottom;i>=top;i--)//left
			PRINT(matrix[i][left]);
		left++;
	}
}

int 
main()
{
	int m[3][4] = {1,2,3,4,
		      10,11,12,5,
		      9,8,7,6};

	int i,j;
	spiral_matrix_print(m,3,4);
	return 0;
}

好多公司面试的时候会让写这个小程序,闲着没事写了一个。 

这个是简单的从原点开始的顺时针打印。当然逆时针的稍微改下就ok了。

 如果可以任意设置起始点的话,就不能用这种方法了。

写个简单的螺旋打印矩阵程序-C

原文:http://www.cnblogs.com/hojor/p/4422725.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!