Print a given matrix in reverse spiral form in C++


In this problem, we are given a 2-dimensional matrix. Our task is to print all the elements of the matrix in reverse spiral form.

Let’s take an example to understand the problem

Input:
   12 23 54 67
   76 90 01 51
   43 18 49 5
   31 91 75 9
Output: 18 49 1 90 76 43 31 91 75 9 5 51 67 54 23 12

We will start from the center of the matrix and print elements in reverse spiral direction taking four loops for printing elements in reverse direction.

Example

Program to show the implementation of our solution

 Live Demo

#include <iostream>
#define R 3
#define C 6
using namespace std;
void printReverseSpiral(int m, int n, int a[R][C]) {
   long int b[100];
   int i, k = 0, l = 0;
   int z = 0;
   int size = m*n;
   while (k < m && l < n) {
      int val;
      for (i = l; i < n; ++i){
         val = a[k][i];
         b[z] = val;
         ++z;
      }
      k++;
      for (i = k; i < m; ++i){
         val = a[i][n-1];
         b[z] = val;
         ++z;
      }
      n--;
      if ( k < m){
         for (i = n-1; i >= l; --i){
            val = a[m-1][i];
            b[z] = val;
            ++z;
         }
         m--;
      }
      if (l < n){
         for (i = m-1; i >= k; --i){
            val = a[i][l];
            b[z] = val;
            ++z;
         }
         l++;
      }
   }
   for (int i=size-1 ; i>=0 ; --i){
      cout<<b[i]<<" ";
   }
}
int main() {
   int mat[R][C] = {
      {34, 5, 6, 98, 12, 23},
      {9, 12, 56, 87, 99, 1},
      {13, 91, 50, 8, 21, 2}
   };
   cout<<"Printing reverse Spiral of the matrix :\n";
   printReverseSpiral(R, C, mat);
   return 0;
}

Output

Printing reverse Spiral of the matrix −

99 87 56 12 9 13 91 50 8 21 2 1 23 12 98 6 5 34

Updated on: 27-Jan-2020

303 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements