Given an M × N integer 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 ]

Practice this problem

 
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. Four loops are used to maintain the spiral order, each for the top, right, bottom, and left corner of the matrix.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


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

Java


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]

Python


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]

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