[AlgoExpert] Spin Rings

Spin Rings

  • Time : O(nm)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void spinRings(vector<vector<int>> &array, int start = 0) {
int n = array.size(), m = array[0].size();
if(min(n,m) / 2 == start) return;
int sy = start, ey = n - start - 1, sx = start, ex = m - start - 1;
int tmp = array[start][start];
for(int i = sy; i < ey; i++) {
array[i][sx] = array[i+1][sx];
}
for(int i = sx; i < ex; i++) {
array[ey][i] = array[ey][i+1];
}
for(int i = ey; i > sy; i--) {
array[i][ex] = array[i-1][ex];
}
for(int i = ex; i > sx; i--) {
array[sy][i] = array[sy][i-1];
}
array[sy][sx+1] = tmp;

spinRings(array, start + 1);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/AlgoExpert/spin-rings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.