旋转矩阵

  我的思维里,矩阵的左上角是开始的位置。现在我遇到一个问题,矩阵的显示和我实际看到的情况不符。

  笛卡尔坐标系中,原点在左下角,我要把某些元素从左下角开始显示出来,也就是说左下角才是开始位置。这就和矩阵的不同了。有时候总是混淆,把位置搞错。现在写了rotateArray函数来旋转这个矩阵,使我们输入矩阵时不用再考虑它的输出会是什么样的。因为处理的结果就是:我们输入的矩阵和我们看到的显示在外观上是一样的。

  下面是rotateArray函数和测试代码:

rotateArray.cpp
 1 #include <iostream>
 2 #include <cstdlib>
 3 //旋转矩阵,主要方便测试
 4 //比如想测试
 5 // y轴 
 6 // |1 2 3
 7 // |4 5 6
 8 // |7 2 6
 9 // 0------>X轴 
10 //若是正常写测试数组的话,要写成
11 // int arrary[3][3] ={
12 //    {7,4,1},
13 //    {2,5,2},
14 //    {6,6,3},
15 // };
16 //但是这样写,我们看着很不方便
17 //用rotateArray就可以写成正常看的形式
18 // int myarray[3][3] ={
19 //    {1,2,3},
20 //    {4,5,6},
21 //    {7,2,6},
22 // }; 
23 //经过转换,myarray和array就相同了,我们就不用操心数组和我们看到的显示不同的问题了 
24 using namespace std;
25 int array[][5] = {
26     {1,2,3,4,5},
27     {6,7,3,4,7},
28     {3,5,4,8,0},
29     {4,2,5,9,3},
30     {5,4,5,5,5},
31 };
32 void roateArray(int arr[][5])
33 {
34     for(int x = 0;x < 3;x++){
35         for(int y = 0;y < 5;y++){
36             int temp = arr[x][y];
37             arr[x][y] = arr[4-x][y];
38             arr[4-x][y] = temp;
39         }
40     }
41     for(int x = 0;x < 5;x++){
42         for(int y = 0;y < x;y++){
43             int temp = arr[x][y];
44             arr[x][y] = arr[y][x];
45             arr[y][x] = temp;
46         }
47     }
48 }
49 void printArray(int arr[][5])
50 {
51     for(int i = 0;i < 5;i++){
52         for(int j = 0;j < 5;j++)
53             cout<<array[i][j]<<" ";
54             cout<<endl;
55     }
56 }
57 int main()
58 {
59     cout<<"----the original array----------"<<endl;
60     printArray(array);    
61     roateArray(array);
62     cout<<"----the rotate  array----------"<<endl;
63     printArray(array);
64     system("pause");
65     return 0;
66 }
原文地址:https://www.cnblogs.com/imoon/p/2628881.html