Given you a n*m matrix, you task is to output the corresponding Spiral matrix whose row is n and column is m.
For example:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Input
The input consists of two integers n and m. (1≤n,m≤200))
Output
Output the corresponding Spiral matrix.
Sample Input
5 5
Sample Output
1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8
13 12 11 10 9
#include<stdio.h>
#include<string>
#include<cstring>
int main()
{
int n,m,flag=0,a[40001],b[200][200];
while(scanf("%d%d",&n,&m)!=EOF){
int i=0,j=0;
for(i=1;i<=m*n;i++)
a[i]=i;
i=0;
j=0;
flag=0;
int x=n;
int y=m;
memset(b,0,sizeof(b));
for(int k=1;k<=m*n;k++)
{
if(flag==0)
{
b[i][j]=a[k];
//printf("%d\n",b[i][j]);
if(j==m-1||b[i][j+1])
{
flag=1;
i++;
continue;
}
// b[i][j]=a[k];
j++;
}
//printf("j=%d\n",j);
else if(flag==1)
{
b[i][j]=a[k];
if(i==n-1||b[i+1][j])
{
flag=2;
j--;
continue;
}
//b[i][j]=a[k];
i++;
}
else if(flag==2)
{
b[i][j]=a[k];
if(k==2*m+n-2||b[i][j-1])
{
flag=3;
i--;
continue;
}
//b[i][j]=a[k];
j--;
}
else if(flag==3)
{
//i--;
b[i][j]=a[k];
if(b[i-1][j])
{
flag=0;
j++;
continue;
}
//b[i][j]=a[k];
i--;
}
}
for(i=0;i<n;i++){
for(j=0;j<m;j++){
printf("%d",b[i][j]);
if(j!=m-1)
printf(" ");
}
printf("\n");
}
}
//system("pause");
return 0;
}