1260. Shift 2D Grid*
https://leetcode.com/problems/shift-2d-grid/
题目描述
Given a 2D grid of size m x n
and an integer k
. You need to shift the grid k
times.
In one shift operation:
- Element at
grid[i][j]
becomes atgrid[i][j + 1]
. - Element at
grid[i][n - 1]
becomes atgrid[i + 1][0]
. - Element at
grid[n - 1][n - 1]
becomes atgrid[0][0]
.
Return the 2D grid after applying shift operationk
times.
具体的例子看 Leetcode.
C++ 实现 1
把矩阵看成 1D 的数组, 会发现就是数据的循环移动…
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
if (grid.empty() || grid[0].empty()) return {};
int m = grid.size(), n = grid[0].size(), size = m * n;
if (k % size == 0) return grid;
k %= size;
vector<int> tmp;
for (int i = size - 1; i > size - 1 - k; -- i)
tmp.push_back(grid[i / n][i % n]);
for (int i = size - 1 - k; i >= 0; -- i)
grid[(i + k) / n][(i + k) % n] = grid[i / n][i % n];
for (int i = 0; i < k; ++i)
grid[i / n][i % n] = tmp[k - 1 - i];
return grid;
}
};
C++ 实现 2
来自 LeetCode Submission.
class Solution {
public:
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
int sx = grid[0].size();
int sy = grid.size();
int os = sx * sy;
vector<vector<int>> result(sy, vector<int>(sx));
for (int y = 0; y < sy; y++) {
for (int x = 0; x < sx; x++) {
int index = (y * sx + x + k) % os;
result[index/sx][index%sx] = grid[y][x];
}
}
return result;
}
};