不额外申请内存(另外的一个二维数组空间),将一个方阵(二维数组)原地旋转90度,主要的思路是,由外向内,一圈圈的进行旋转(就是依次进行交换),如下图所示,当这些圈圈都交换完了之后,就完成了原地旋转了。
代码如下:
1 #include <time.h> 2 #include <stdlib.h> 3 #include <iostream> 4 using namespace std; 5 #define MIN 0 6 #define MAX 9 7 8 9 void rotate(int **matrix, int size); 10 void new_matrix(int ** matrix, int size); 11 void delete_matrix(int ** matrix, int size); 12 void rand_matrix(int ** matrix, int size); 13 void print_matrix(int ** matrix, int size); 14 int main() { 15 16 int size = 5; 17 int **matrix = new int *[size]; 18 new_matrix(matrix, size); 19 srand((unsigned)(time(0))); 20 rand_matrix(matrix, size); 21 print_matrix(matrix, size); 22 cout << "***************" << endl; 23 rotate(matrix, size); 24 print_matrix(matrix, size); 25 delete_matrix(matrix, size); 26 delete []matrix; 27 getchar(); 28 getchar(); 29 return 0; 30 } 31 void rotate(int **matrix, int size) 32 { 33 int temp; 34 for (int i = 0; i < size / 2; i++) 35 { 36 int first = i; 37 int last = size - 1 - i; 38 for (int j = first; j < last; j++) 39 { 40 int offset = size - 1 - j; 41 int temp = matrix[j][i]; 42 matrix[j][i] = matrix[last][j]; 43 matrix[last][j] = matrix[offset][last]; 44 matrix[offset][last] = matrix[i][offset]; 45 matrix[i][offset] = temp; 46 } 47 } 48 } 49 void new_matrix(int ** matrix, int size) 50 { 51 for (int i = 0; i < size; i ++) 52 { 53 matrix[i] = new int[size]; 54 } 55 } 56 void delete_matrix(int ** matrix, int size) 57 { 58 for (int i = 0; i < size; i ++) 59 { 60 delete[] matrix[i]; 61 } 62 } 63 void rand_matrix(int ** matrix, int size) 64 { 65 for (int i = 0; i < size; i ++) 66 { 67 for (int j = 0; j < size; j ++) 68 { 69 matrix[i][j] = MIN + rand() % (MAX - MIN + 1); 70 } 71 72 } 73 } 74 void print_matrix(int ** matrix, int size) 75 { 76 for (int i = 0; i < size; i ++) 77 { 78 for (int j = 0; j < size; j ++) 79 { 80 cout << " " << matrix[i][j]; 81 } 82 cout << endl; 83 } 84 }
代码中还涉及到了通过new与delete分配与释放一个二维数组,也是面试中的一个问题。