Create Spiral Matrix from given Array

Given an array containing M*N elements, construct a M x 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 ]

 

 
This problem is mainly reverse of below problem.

Print Matrix in Spiral Order

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

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]

 
The time complexity of above solution is O(M*N).

 
Exercise: Write recursive solution of above problem.

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
trackback

neat solution