我是 C++ 新手,正在编写以下代码,该代码旋转给定的二维矩阵。我的代码可以正常旋转一圈。然后我在代码中添加了一个 while 循环以使其更通用,我注意到 while 代码无论如何都不会进行更多迭代。我试图把
return MatrixRotateOutPut
带出来,但后来就未知了。
我还尝试在 while 循环后添加
return 0
但它给了我另一个错误。我还检查了这两个链接(Link 1,Link 2),但它们对我来说并没有多大帮助。
#include<iostream>
#include<vector>
using namespace std;
int MatrixPrint2D(vector<vector<int>> Input) {
for (int i = 0; i < Input.size(); i++) {
for (int j = 0; j < Input[0].size(); j++) {
printf("%d ", Input[i][j]);
}
printf("\n");
}
}
vector<vector<int>> MatrixRotate(vector<vector<int>> Input, int Irritation) {
while (Irritation > 0) {
cout << Irritation << "\n" << endl;
vector<vector<int>> MatrixRotateOutPut(Input[0].size(), vector<int>(Input.size(), 1));
for (int i = 0; i < Input.size(); i++) {
for (int j = 0; j < Input[0].size(); j++) {
MatrixRotateOutPut[j][Input.size() - 1 - i] = Input[i][j];
}
}
vector<vector<int>> Input(MatrixRotateOutPut.size(), vector<int>(MatrixRotateOutPut[0].size(), 1));
Input = MatrixRotateOutPut;
MatrixPrint2D(MatrixRotateOutPut);
printf("\n");
Irritation--;
return MatrixRotateOutPut;
}
}
int main() {
//Define a matrix for testing:
vector<vector<int>> Matrix2(4, vector<int>(5, 1));
int R = 2;
int C = 4;
vector<vector<int>> MatrixInput(R, vector<int>(C, 1));;
for (int i = 0; i < MatrixInput.size(); i++) {
for (int j = 0; j < MatrixInput[0].size(); j++) {
int temp;
temp = i ^ (2 * j);
MatrixInput[i][j] = temp;
}
}
cout << "MatrixInput:" << endl;
MatrixPrint2D(MatrixInput);
printf("\n");
vector<vector<int>> OutPut2 = MatrixRotate(MatrixInput, 4);
return 0;
}
您可以执行以下操作:
所以:
vector<vector<int>> MatrixRotate(vector<vector<int>> Input, int Irritation) {
vector<vector<int>> MatrixRotateOutPut;
while (Irritation > 0) {
cout << Irritation << "\n" << endl;
MatrixRotateOutPut = vector<vector<int>>(Input[0].size(), vector<int>(Input.size(), 1));
for (int i = 0; i < Input.size(); i++) {
for (int j = 0; j < Input[0].size(); j++) {
MatrixRotateOutPut[j][Input.size() - 1 - i] = Input[i][j];
}
}
vector<vector<int>> Input(MatrixRotateOutPut.size(), vector<int>(MatrixRotateOutPut[0].size(), 1));
Input = MatrixRotateOutPut;
MatrixPrint2D(MatrixRotateOutPut);
printf("\n");
Irritation--;
}
return MatrixRotateOutPut;
}