b_lc_循环轮转矩阵(规律 + 双向队列)
返回执行 k 次逆时针循环轮转操作后的矩阵。
2 <= m, n <= 50,1 <= k <= 109
思路:每一环的宽:n-2i,2i是因为,每次要在左、右边都留出i个位置,所以乘以2
class Solution {
public:
vector<int> change(vector<int> a, int k) {
deque<int> q(a.begin(), a.end());
k %= a.size();
while (k--) {
int v = q.front(); q.pop_front();
q.push_back(v);
}
vector<int> ans(q.begin(), q.end());
return ans;
}
vector<vector<int>> rotateGrid(vector<vector<int>>& g, int k) {
int n = g.size(), m = g[0].size();
int round = min(n, m) / 2;
int i = 0, j = 0;
while (round--) {
int idx = 0;
vector<int> data((n - 2*i) * (m - 2*j) - (n - 2*(i+1)) * (m - 2*(j+1)));
for (int y = j; y < m - j - 1; y++) {
data[idx++] = g[i][y];
}
for (int x = i; x < n - i - 1; x++) {
data[idx++] = g[x][m-j-1];
}
for (int y = m - j - 1; y > j; y--) {
data[idx++] = g[n-i-1][y];
}
for (int x = n - i - 1; x > i; x--) {
data[idx++] = g[x][j];
}
auto after = change(data, k);
idx = 0;
for (int y = j; y < m - j - 1; y++) {
g[i][y] = after[idx++];
}
for (int x = i; x < n - i - 1; x++) {
g[x][m-j-1] = after[idx++];
}
for (int y = m - j - 1; y > j; y--) {
g[n-i-1][y] = after[idx++];
}
for (int x = n - i - 1; x > i; x--) {
g[x][j] = after[idx++];
}
i++, j++;
}
return g;
}
};