您的位置:首页 > 其它

打印螺旋矩阵

2012-07-25 21:57 253 查看
see: http://www.geeksforgeeks.org/archives/10768


Print a given matrix in spiral form

August 20, 2011

Given a 2D array, print it in spiral form. See the following examples.

Input:
1    2   3   4
5    6   7   8
9   10  11  12
13  14  15  16
Output:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

Input:
1   2   3   4  5   6
7   8   9  10  11  12
13  14  15 16  17  18
Output:
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11


Answer:

/* Paste your code here (You may delete these lines if not writing code) */
void spiralmatrix(int arr[], int m, int n)
{
int rowstart=0, rowend=m-1, colstart=0, colend=n-1;
int i,j;
while(rowstart<=rowend&&colstart<=colend)
{
int i=rowstart, j=colstart;
for(j=colstart;j<=colend;j++)
{
printf("%d",arr[i][j]);
}
for(i=rowstart+1,j--;i<=rowend;i++)
{
printf("%d",arr[i][j]);
}
for(j=colend-1,i--;j>=colstart;j--)
{
printf("%d",arr[i][j]);
}
for(i=rowend-1,j++;i>=rowstart+1;i--)
{
printf("%d",arr[i][j]);
}
rowstart++, rowend--, colstart++,colend--;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: