思想
将整个旋转过程转化为由外向内逐层旋转
使用四个指针LR,LC,RR,RC
(LR,LC)标记正方形左上角位置坐标
(RR,RC)标记正方形右下角位置坐标
times = RR - LR用来计算这一层需要调换的次数
旋转函数(顺时针旋转90°)
void rotate(int **arr, int LR, int LC, int RR, int RC){
int times = RR - LR;
for(int i = 0; i < times; i++){
int temp = arr[LR][LC+i];
arr[LR][LC+i] = arr[RR-i][LC];
arr[RR-i][LC] = arr[RR][RC-i];
arr[RR][RC-i] = arr[LR+i][RC];
arr[LR+i][RC] = temp;
//outputArr(arr, 3, 3);
}
}
相关阅读
旋转正方形矩阵
螺旋打印矩阵
Z字打印矩阵
行列排序矩阵找数
完整代码
#include <bits/stdc++.h>
using namespace std;
int **inputArr(int n, int m){
int **arr;
arr = new int* [n];
for(int i = 0; i < n; i++){
arr[i] = new int [m];
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> arr[i][j];
}
}
return arr;
}
void outputArr(int **arr, int n, int m){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cout << arr[i][j] << " ";
}
cout << endl;
}
}
void rotate(int **arr, int LR, int LC, int RR, int RC){
int times = RR - LR;
for(int i = 0; i < times; i++){
int temp = arr[LR][LC+i];
arr[LR][LC+i] = arr[RR-i][LC];
arr[RR-i][LC] = arr[RR][RC-i];
arr[RR][RC-i] = arr[LR+i][RC];
arr[LR+i][RC] = temp;
//outputArr(arr, 3, 3);
}
}
int main(){
int **arr;
int n;
cin >> n;
arr = inputArr(n, n);
int LR = 0, LC = 0;
int RR = n-1, RC = n-1;
while(LR != RR || LC != RC){
rotate(arr,LR++,LC++,RR--,RC--);
}
outputArr(arr, n, n);
}