Tuesday, 12 December 2017

Printing a matrix in spiral order(Spiral Matrix)

       In this post,We will see how to print a matrix in spiral format of clockwise direction.

If the matrix of 3×3 is  [1 2 3
                                           4 5 6
                                           7 8 9]
Then it is printed in spiral format in clockwise direction as , 1 2 3 6 9 8 7 4 5.

         
 If the matrix is of 4×4 or higher ,it should be printed in the following order.




                                
 -> First ,We should start from left to right direction. Where dir=0.

->  Then ,from top to bottom direction.
       Where dir=1.
->Then ,from right to left direction.Where 
    dir=2.
 
->Then ,from bottom to top.Where dir=3.

Here, the variable 'dir' is used to specify the direction.

->The variables  'T' (top) -> points 0th row.

->The variable 'B' (bottom)-> points to mth row.

->The variable 'L' (left)-> points to 0th column.

->The variable 'R' (right)-> points to nth column.


Program:

#include<iostream>
using namespace std;
int main()
{
   int Mat[10][10];
    int dir=0;
    int T,B,L,R;
    int m,n;
    cout<<"Give the order of the matrix"<<endl;
    cin>>m>>n;

    T=0;
    B=m-1;
    L=0;
    R=n-1;
    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
            cin>>Mat[i][j];
    while(T<=B && L<=B)
    {
        if(dir==0)  
        {
            for(int k=L;k<=R;k++)
                cout<<Mat[T][k];
            T++;
        }
        if(dir==1)
        {
            for(int k=T;k<=B;k++)
                 cout<<Mat[k][R];
            R--;
        }
        if(dir==2)

        {
            for(int k=R;k>=L;k--)
                cout<<Mat[B][k];
            B--;
        }
        if(dir==3)
        {
            for(int k=B;k>=T;k--)
                cout<<Mat[k][L];
            L++;
        }
        dir=(dir+1)%4;
    }
}



Output:




No comments:

Post a Comment