Skip to main content

Spirally Traversing a Matrix

Task: Given a M*N matrix, Traverse and print the values of matrix in spiral form.

Example:
1
4 4
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

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. using namespace std;
  3. void spiralForm(int a[][10],int i1,int i2,int j1,int j2)
  4. {
  5.     if(i1==i2)
  6.     {
  7.         while(j1<=j2)
  8.         {
  9.             cout<<a[i1][j1]<<" "; 
  10.             j1++;
  11.         }
  12.         return;
  13.     }
  14.     else if(j1==j2)
  15.     {
  16.         while(i1<=i2)
  17.         {
  18.             cout<<a[i1][j1]<<" ";
  19.             i1++;
  20.         }
  21.         return;
  22.     }
  23.     else
  24.     {
  25.         int i,j;
  26.         i=i1,j=j1;
  27.         while(j<=j2)
  28.         {
  29.             cout<<a[i][j]<<" ";
  30.             j++;
  31.         }
  32.         i++,j--;
  33.         while(i<=i2)
  34.         {
  35.             cout<<a[i][j]<<" ";
  36.             i++;
  37.         }
  38.         i--,j--;
  39.         while(j>=j1)
  40.         {
  41.             cout<<a[i][j]<<" ";
  42.             j--;
  43.         }
  44.         i--,j++;
  45.         while(i>=i1+1)
  46.         {
  47.             cout<<a[i][j]<<" ";
  48.             i--;
  49.         }
  50.         if(i1+1>i2-1||j1+1>j2-1)
  51.         {
  52.             return;
  53.         }
  54.         else
  55.         {
  56.             spiralForm(a,i1+1,i2-1,j1+1,j2-1);
  57.         }
  58.     }
  59. }
  60. int main()
  61.  {
  62. int t;
  63. cin>>t;
  64. while(t--)
  65. {
  66.     int m,n;
  67.     cin>>m>>n;
  68.     int a[m][10];
  69.     for(int i=0;i<m;i++)
  70.     {
  71.         for(int j=0;j<n;j++)
  72.         {
  73.             cin>>a[i][j];
  74.         }
  75.     }
  76.     spiralForm(a,0,m-1,0,n-1);
  77.     cout<<endl;
  78. }
  79. return 0;
  80. }

Here is the Video: