Given an integer array containing M × N elements, construct an M × N matrix from it in spiral order.

For example,

Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 
Output:
 
[ 1   2   3   4   5 ]
[ 16  17  18  19  6 ]
[ 15  24  25  20  7 ]
[ 14  23  22  21  8 ]
[ 13  12  11  10  9 ]

Practice this problem

This problem is mainly the reverse of the following problem:

Print matrix in spiral order

 
The idea remains the same – read elements from the given array one by one and fill the matrix in spiral order. Four loops are used to maintain the spiral order, each for the top, right, bottom, and left corner of the matrix.

Following is the implementation in C++, Java, and Python based on the above idea:

C++


Download  Run Code

Output:

  1   2   3   4   5
  16  17  18  19  6
  15  24  25  20  7
  14  23  22  21  8
  13  12  11  10  9

Java


Download  Run Code

Output:

[ 1, 2, 3, 4, 5]
[16, 17, 18, 19, 6]
[15, 24, 25, 20, 7]
[14, 23, 22, 21, 8]
[13, 12, 11, 10, 9]

Python


Download  Run Code

Output:

[ 1, 2, 3, 4, 5]
[16, 17, 18, 19, 6]
[15, 24, 25, 20, 7]
[14, 23, 22, 21, 8]
[13, 12, 11, 10, 9]

The time complexity of the proposed solution is O(M × N) for an M × N matrix and doesn’t require any extra space.

 
Exercise: Write recursive solution of above problem.