#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了。
如果可以任意设置起始点的话,就不能用这种方法了。