Friday, 21 July 2017

Write a C program to print the elements of a square matrix in spiral order from the center.

                                             Spiral Matrix 
Assume the size of the matrix is odd.
Sample Input:
3
1 2 3
4 5 6
7 8 9
Sample Output:
5 4 7 8 9 6 3 2 1 
                                            C-Solution
#include<stdio.h>
int main()
{
 int n,i,j;
 scanf("%d",&n);int a[n][n],b[n*n],c=0;
 for(i=0;i<n;i++)
 {
     for(j=0;j<n;j++)
     {
         scanf("%d",&a[i][j]);//printf("%d ",a[i][j]);
     }
 }
 
 int top=0,bottom=n-1,left=0,right=n-1,direction=0;
     while(top<=bottom&&left<=right)
    {
        if(direction==0)
        {
            for(i=left;i<=right;i++){
            b[c]=a[top][i];c++;
                //printf("%d ",b[c-1]);
            }
            top++;
        }
         else if(direction==1)
        {
            for(i=top;i<=bottom;i++)
            {
                b[c]=a[i][right];c++;
                //printf("%d",b[c-1]);
            }
            right--;
        }
         else if(direction==2)
        {
            for(i=right;i>=left;i--)
            {
                b[c]=a[bottom][i];c++;
              //  printf("%d",b[c-1]);
            }bottom--;
    }
        else  if(direction==3)
        {
            for(i=bottom;i>=top;i--)
            {
                b[c]=a[i][left];c++;
             //   printf("%d",b[c-1]);
            }left++;
          

        }
       direction=(direction+1)%4;
        
    }
 for(i=c-1;i>=0;i--)
 {     printf("%d ",b[i]);
 }
 return 0;
}

No comments:

Post a Comment