用 C++ 转换 2D 网格
假设我们有一个 m x n 大小的二维网格。我们还有另一个变量 k。我们必须将网格移动 k 次。移动操作如下
网格 G[i, j] 中的元素移动到 G[i, j + 1]
网格 G[i, n - 1] 中的元素移动到 G[i + 1, 0]
网格 G[m - 1, n - 1] 中的元素移动到 G[0, 0]
如果网格类似于 -
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
输出将是 -
| 9 | 1 | 2 |
| 3 | 4 | 5 |
| 6 | 7 | 8 |
要解决这个问题,我们将遵循以下步骤 -
移动操作将把矩阵作为输入
n = 行数,m := 列数,x := 右下角元素
对于 i := n - 1 到 0
对于 j := m - 1 到 0
如果 j = 0 且 i > 0,则 G[i, j] := G[i - 1, m - 1]
否则,如果 j > 0,则 G[i, j] := G[i, j - 1]
G[0, 0] := x
按以下规则调用移动操作 -
当 k 不为 0 时
移动网格 G
k 减 1
返回网格 G
示例 (C++)
我们来看一下下面的实现,以便更好地理解 -
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] <<", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
void shift(vector<vector<int>>& grid){
int n = grid.size();
int m = grid[0].size();
int x = grid[n-1][m-1];
for(int i = n-1; i>=0; i--){
for(int j = m-1;j>=0;j--){
if(j == 0 && i>0){
grid[i][j] = grid[i-1][m-1];
}
else if(j>0){
grid[i][j] = grid[i][j-1];
}
}
}
grid[0][0] = x;
}
vector<vector<int>> shiftGrid(vector<vector<int>>& g, int k) {
while(k--){
shift(g);
}
return g;
}
};
main(){
Solution ob;
vector<vector<int>> mat = {{1,2,3},{4,5,6},{7,8,9}};
print_vector(ob.shiftGrid(mat, 1));
}输入
{{1,2,3},{4,5,6},{7,8,9}}
1输出
[[9, 1, 2, ],[3, 4, 5, ],[6, 7, 8, ],]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP