using System;
using System.Collections.Generic;
class GfG {
// Fills temp array into mat using spiral order traversal.
// Used inside the main function spiralRotate()
void FillSpiral(int[,] mat, List<int> temp) {
int m = mat.GetLength(0);
int n = mat.GetLength(1);
int k = 0, l = 0;
// Index in temp array
int tIdx = 0;
while (k < m && l < n) {
// first row from the remaining rows
for (int i = l; i < n; ++i)
mat[k, i] = temp[tIdx++];
k++;
// last column from the remaining columns
for (int i = k; i < m; ++i)
mat[i, n - 1] = temp[tIdx++];
n--;
// last row from the remaining rows
if (k < m) {
for (int i = n - 1; i >= l; --i)
mat[m - 1, i] = temp[tIdx++];
m--;
}
// first column from the remaining columns
if (l < n) {
for (int i = m - 1; i >= k; --i)
mat[i, l] = temp[tIdx++];
l++;
}
}
}
void SpiralRotate(int[,] mat, int k) {
int m = mat.GetLength(0);
int n = mat.GetLength(1);
// Temporary array to store elements in the spiral order
List<int> temp = new List<int>();
int s = 0, l = 0;
while (s < m && l < n) {
// Record the start position of the current ring
int start = temp.Count;
// copy the first row from the remaining rows
for (int i = l; i < n; ++i)
temp.Add(mat[s, i]);
s++;
// copy the last column from the remaining columns
for (int i = s; i < m; ++i)
temp.Add(mat[i, n - 1]);
n--;
// copy the last row from the remaining rows
if (s < m) {
for (int i = n - 1; i >= l; --i)
temp.Add(mat[m - 1, i]);
m--;
}
// copy the first column from the remaining columns
if (l < n) {
for (int i = m - 1; i >= s; --i)
temp.Add(mat[i, l]);
l++;
}
int ringSize = temp.Count - start;
// Adjust k to rotate only within the current ring
int kNew = k % ringSize;
// Rotate the current ring using the reversal algorithm
Reverse(temp, start, temp.Count);
Reverse(temp, start, start + kNew);
Reverse(temp, start + kNew, temp.Count);
}
// Fill the matrix back using the temp array
FillSpiral(mat, temp);
}
void Reverse(List<int> arr, int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end - 1];
arr[end - 1] = temp;
start++;
end--;
}
}
static void Main(string[] args) {
GfG solution = new GfG();
int k = 5;
int[,] mat = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 },
{ 13, 14, 15, 16 }
};
solution.SpiralRotate(mat, k);
for (int i = 0; i < mat.GetLength(0); i++) {
for (int j = 0; j < mat.GetLength(1); j++) {
Console.Write(mat[i, j] + " ");
}
Console.WriteLine();
}
}
}