Skip to main content

Posts

Showing posts with the label Spirally Traversing a Matrix

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++: #include<iostream> using namespace std; void spiralForm(int a[][10],int i1,int i2,int j1,int j2) {     if(i1==i2)     {         while(j1<=j2)         {             cout<<a[i1][j1]<<" ";              j1++;         }         return;     }     else if(j1==j2)     {         while(i1<=i2)         {             cout<<a[i1][j1]<<" ";             i1++;         }         return;     }     else     {         int i,j;         i=i1,j=j1;         while(j<=j2)         {             cout<<a[i][j]<<" ";             j++;         }         i++,j--;         while(i<=i2)         {             cout<<a[i][j]<<" ";             i++;         }         i--,j--;         while(j>=j1)         {