Traversing a matrix in spiral order

Given a Matrix, write a function that will print the elements in spiral order. For example, if the Matrix is as below:

Then the output should be:
1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10
Which is the spiral order of given matrix:

Solution:

The given matrix is below:

 

In a single loop we will print one complete circle of elements. Hence we will have 4 loops inside a bigger loop to print the

1. Top Row from Left to Right 2. Last Column from Top to bottom 3. Last Row from Right to Left 4. First Column Bottom to Top

So first pass (of outer loop, which has the above 4 loops) the elements will get printed as below:

In the next loop we will print the inner circle

And so on..

Code:
void spiralTraversal(int **a, int n)
{
    int rs=0, cs=0;     // RowStart and Column Start
    int re=n-1, ce=n-1;  // RowEnd & columnEnd
    while(rs<=re && cs<=ce)
    {
        int i=rs, j=cs;
        for(j=cs; j<=ce; j++)
            cout<<" "<<a[i][j];
        for(i=rs+1, j--; i<=re; i++)
            cout<<" "<<a[i][j];
        for(j=ce-1, i--; j>=cs; j--)
            cout<<" "<<a[i][j];
        for(i=re-1, j++; i>=rs+1; i--)
            cout<<" "<<a[i][j];
        rs++; cs++; re--; ce--;
    }
}
 

0 Comments

Leave a comment