注意:
您必须旋转图像 到位,这意味着您必须直接修改输入2D矩阵。 不要 分配另一个2D矩阵并进行旋转。
Example 1: Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix 到位 such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ]
我们可以通过2种不同的方式解决此问题。
- 通过反转和交换
- 通过翻转
1.旋转和交换元素。
在此解决方案中,我们首先反转数组,表示1ST 行将转到3rd 行和3rd 排将进入第一排。
因此,如果我们的输入是:
1 2 3 4 5 6 7 8 9
反转数组后,输出为:
7 8 9 4 5 6 1 2 3
然后对角地交换元素,在此步骤之后,输出将是:
7 4 1 8 5 2 9 6 3
因此,我们的最终结果。
2.通过翻转
在此解决方案中,我们将阵列翻转2次。一个是对角翻转,第二个是水平翻转。
如果我们的原始数组是:
1 2 3 4 5 6 7 8 9
对角翻转后,输出为:
1 4 7 2 5 8 3 6 9
在水平翻转之后,输出将是:
7 4 1 8 5 2 9 6 3
最终数组。
C ++解决方案
#include<iostream> #include<vector> using namespace STd; void rotate(vector<vector<int> >& myMatrix) { reverse(myMatrix.begin(), myMatrix.end()); int size = myMatrix.size(); for (int i = 0; i < size; ++i) { for (int j = i+1; j < size; ++j) { swap(myMatrix[i][j], myMatrix[j][i]); } } } void flip(vector<vector<int> >& myMatrix) { int size = myMatrix.size(); /*Flip Diagonally*/ for (size_t i = 0; i < size; i++) { for (size_t j = i; j < size; j++) { swap(myMatrix[i][j], myMatrix[j][i]); } } /* flip horizontally */ for (size_t i = 0; i < size; i++) { reverse(myMatrix[i].begin(), myMatrix[i].end()); } } int main() { //Declare a 2d array vector<vector<int> > myMatrix; int row = 3; int column = 3; int temp = 1; // variable to put the values in to vector //populate the array for(int i=0; i < row; i++) { //create a temp vector, it will act as a row vector<int> temp_vector; for(int i=0; i<column; i++) { temp_vector.push_back(temp); temp++; } // push the content of temp vector to the main vector myMatrix.push_back(temp_vector); } cout<< "Entered vector is : "<<endl; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) cout << myMatrix[i][j] << ' '; cout << endl; } //rotate(myMatrix); flip(myMatrix); cout<< "Final vector is : "<<endl; for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) cout << myMatrix[i][j] << ' '; cout << endl; } return 0; }
Output: Entered vector is : 1 2 3 4 5 6 7 8 9 Final vector is : 7 4 1 8 5 2 9 6 3
在下面的评论部分中分享您的解决方案。
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |