![]() |
VOOZH | about |
Given a matrix of order m*n and a value k, the task is to rotate each ring of the matrix clockwise by k.
Examples:
Input :k = 3
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4Input : k = 2
1 2 3 4
10 11 12 5
9 8 7 6
Output:
9 10 1 2
8 11 12 3
7 6 5 4
We simply use the solution of clockwise rotate by one and call it in a loop.
15 14 13 9 16 10 6 5 12 11 7 1 8 4 3 2
The idea is to traverse matrix in spiral form. Here is the algorithm to solve this problem :
- Make an auxiliary array temp[] of size m*n.
- Start traversing matrix in spiral form and store elements of current ring in temp[] array. While storing the elements in temp, keep track of starting and ending positions of current ring.
- For every ring that is being stored in temp[], right rotate that subarray temp[]
- Repeat this process for each ring of matrix.
- In last traverse matrix again spirally and copy elements of temp[] array to matrix..
15 14 13 9 16 10 6 5 12 11 7 1 8 4 3 2