C++ 方阵原地旋转90度

时间:2022-09-14 19:22:24

不额外申请内存(另外的一个二维数组空间),将一个方阵(二维数组)原地旋转90度,主要的思路是,由外向内,一圈圈的进行旋转(就是依次进行交换),如下图所示,当这些圈圈都交换完了之后,就完成了原地旋转了。

C++ 方阵原地旋转90度

代码如下:

 #include <time.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define MIN 0
#define MAX 9 void rotate(int **matrix, int size);
void new_matrix(int ** matrix, int size);
void delete_matrix(int ** matrix, int size);
void rand_matrix(int ** matrix, int size);
void print_matrix(int ** matrix, int size);
int main() { int size = ;
int **matrix = new int *[size];
new_matrix(matrix, size);
srand((unsigned)(time()));
rand_matrix(matrix, size);
print_matrix(matrix, size);
cout << "***************" << endl;
rotate(matrix, size);
print_matrix(matrix, size);
delete_matrix(matrix, size);
delete []matrix;
getchar();
getchar();
return ;
}
void rotate(int **matrix, int size)
{
int temp;
for (int i = ; i < size / ; i++)
{
int first = i;
int last = size - - i;
for (int j = first; j < last; j++)
{
int offset = size - - j;
int temp = matrix[j][i];
matrix[j][i] = matrix[last][j];
matrix[last][j] = matrix[offset][last];
matrix[offset][last] = matrix[i][offset];
matrix[i][offset] = temp;
}
}
}
void new_matrix(int ** matrix, int size)
{
for (int i = ; i < size; i ++)
{
matrix[i] = new int[size];
}
}
void delete_matrix(int ** matrix, int size)
{
for (int i = ; i < size; i ++)
{
delete[] matrix[i];
}
}
void rand_matrix(int ** matrix, int size)
{
for (int i = ; i < size; i ++)
{
for (int j = ; j < size; j ++)
{
matrix[i][j] = MIN + rand() % (MAX - MIN + );
} }
}
void print_matrix(int ** matrix, int size)
{
for (int i = ; i < size; i ++)
{
for (int j = ; j < size; j ++)
{
cout << " " << matrix[i][j];
}
cout << endl;
}
}

代码中还涉及到了通过new与delete分配与释放一个二维数组,也是面试中的一个问题。