Shift all Matrix Elements by 1 in Spiral Order

Given a M x N matrix, shift all its elements by 1 in spiral order.


 

For example,


Input:

[  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 ]

Output:

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

 
Recommended Read: Print Matrix in Spiral Order
 

We can easily solve this problem by reading elements from the given matrix one by one in spiral order and replacing them with their previous elements. To maintain the spiral order four loops are used, each for top, right, bottom and left corner of the matrix.

 

Download   Run Code

Output:

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

 
Time complexity of above solution is O(M*N) and auxiliary space used by the program is O(1).

 
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  
Notify of