• 旋转正方形矩阵


    Problem:
      旋转正方形矩阵【题目】 给定一个整型正方形矩阵matrix,
      请把该矩阵调整成顺时针旋转90度的样子。
      【要求】 额外空间复杂度为O(1).

    Solution:
      同样,采用由外向内一圈一圈变换,找到元素变换位置的规律即可。
      难点在于区分偶数维矩阵和奇数维矩阵的不同操作

    Code:

      

     1 #pragma once
     2 
     3 #include <iostream>
     4 using namespace std;
     5 
     6 template<class T>
     7 void RotateMatrix(T& arr,const int x, const int y)//使用数组的引用传参,怎可在原数组上进行旋转
     8 {
     9     int lx = 0, ly = 0; //左上角坐标
    10     int rx = x - 1, ry = y - 1;//右下角的坐标
    11 
    12     while (lx < rx || ly < ry)
    13     {
    14 
    15         for (int k = 0; k < ry - ly; ++k)//每一个圈次中所要旋转的元素
    16         {
    17             int temp = arr[lx][ly + k];
    18             arr[lx][ly + k] = arr[rx - k][lx];
    19             arr[rx - k][lx] = arr[rx][ry - k];
    20             arr[rx][ry - k] = arr[lx + k][ry];
    21             arr[lx + k][ry] = temp;
    22         }
    23 
    24         lx += 1;//左上角右下移
    25         ly += 1;
    26         rx -= 1;//右下角左上移
    27         ry -= 1;
    28     }
    29     
    30 }
    31 
    32 void Test()
    33 {
    34     int aa[3][3] = { 1,2,3,4,5,6,7,8,9 };
    35     int bb[4][4] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 };
    36 
    37     RotateMatrix(aa, 3, 3);
    38     for (auto &a : aa)
    39     {
    40         for (auto b : a)
    41             cout << b << "  ";
    42         cout << endl;
    43     }
    44     cout << endl << "******************************" << endl;
    45 
    46     RotateMatrix(bb, 4, 4);
    47     for (auto &a : bb)
    48     {
    49         for (auto b : a)
    50             cout << b << "  ";
    51         cout << endl;
    52     }
    53     cout << endl << "******************************" << endl;
    54 
    55 }
  • 相关阅读:
    BUPT复试专题—最长连续等差子数列(2014软院)
    BUPT复试专题—奇偶求和(2014软件)
    BUPT复试专题—网络传输(2014网研)
    Hopscotch(POJ 3050 DFS)
    Backward Digit Sums(POJ 3187)
    Smallest Difference(POJ 2718)
    Meteor Shower(POJ 3669)
    Red and Black(poj 1979 bfs)
    测试
    Equations(hdu 1496 二分查找+各种剪枝)
  • 原文地址:https://www.cnblogs.com/zzw1024/p/10989042.html
Copyright © 2020-2023  润新知