Print Matrix in spiral way

This algorithm is used to print the array elements in a spiral way. At first starting from the first row, print the whole content and then follow the last column to print, then the last row and so on, thus it prints the elements in spiral fashion. 

The time complexity of this algorithm is O(MN), M is the number of rows and N is the number of columns.

Input and Output

Input:
The matrix:
 1   2   3   4   5   6
 7   8   9  10  11  12
13  14  15  16  17  18

Output:
Contents of an array as the spiral form
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16

Algorithm

dispSpiral(mat, m, n)

Input: The matrix mat, row and column m and n.

Output: Print the elements of the matrix in a spiral way.

Begin
   currRow := 0 and currCol := 0
   while currRow and currCol are in the matrix range, do
      for i in range currCol and n-1, do
         display mat[currRow, i]
      done

      increase currRow by 1
      for i in range currRow and m-1, do
         display mat[i, n-1]
      done

      decrease n by 1
      if currRow 

Example

#include 
#define ROW 3
#define COL 6
using namespace std;

int array[ROW][COL] = {
   {1, 2, 3, 4, 5, 6},
   {7, 8, 9, 10, 11, 12},
   {13, 14, 15, 16, 17, 18}
};

void dispSpiral(int m, int n) {
   int i, currRow = 0, currCol = 0;
   while (currRow = currCol; --i) {
            cout = currRow; --i) {
            cout 

Output

1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16
Updated on: 2020-06-17T10:14:06+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements