Print a matrix in a spiral form starting from a point in C++

C++Server Side ProgrammingProgramming

In this problem, we are a 2d matrix and a point P(c,r). Our task is to print all elements of the matrix in a spiral form (anti-clockwise) that starts from a given point P.

Let’s take an example to understand our problem,

Input: matrix[][] = {{3, 5, 7} }
Output:

To solve this problem, we use 4 loops for printing elements. Each loop prints elements of its own direction. We will start our printing from point p and go on printing the spiral form.

Example

Program to show the implementation of our solution

 Live Demo

#include <iostream>
using namespace std;
const int MAX = 100;
void printSpiralMatrix(int mat[][MAX], int r, int c) {
   int i, a = 0, b = 2;
   int low_row = (0 > a) ? 0 : a;
   int low_column = (0 > b) ? 0 : b - 1;
   int high_row = ((a + 1) >= r) ? r - 1 : a + 1;
   int high_column = ((b + 1) >= c) ? c - 1 : b + 1;
   while ((low_row > 0 - r && low_column > 0 - c)) {
      for (i = low_column + 1; i <= high_column && i < c && low_row >= 0; ++i)
         cout<<mat[low_row][i]<<" ";
      low_row -= 1;
      for (i = low_row + 2; i <= high_row && i < r && high_column < c; ++i)
         cout<<mat[i][high_column]<<" ";
      high_column += 1;
      for (i = high_column - 2; i >= low_column && i >= 0 && high_row < r; --i)
         cout << mat[high_row][i]<<" ";
      high_row += 1;
      for (i = high_row - 2; i > low_row && i >= 0 && low_column >= 0; --i)
         cout<<mat[i][low_column]<<" ";
      low_column -= 1;
   }
   cout << endl;
}
int main() {
   int mat[][MAX] = {
      { 1, 4, 7 },
      { 2, 5, 8 },
      { 3, 6, 9 }
   };
   int r = 3, c = 3;
   cout<<"Sprial traversal of matrix starting from point "<<r<<", "<<c<<" is :\n";
   printSpiralMatrix(mat, r, c);
}

Output

Sprial traversal of matrix starting from point 3, 3 is −

7 8 5 4 9 6 3 2 1
raja
Published on 27-Jan-2020 06:33:03
Advertisements