b_lc_迴圈輪轉矩陣(規律 + 雙向佇列)
阿新 • • 發佈:2021-07-06
返回執行 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; } };