旋转矩阵(leetcode4.7每日打卡)
给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。
不占用额外内存空间能否做到?
示例 1:
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
[
[7,4,1],
[8,5,2],
[9,6,3]
]
示例 2:
给定 matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
借助数组:
1 void rotate(int** matrix, int matrixSize, int* matrixColSize) 2 { 3 int matrix_new[matrixSize][matrixColSize[0]]; 4 5 for(int i = 0; i < matrixSize; i++) 6 { 7 for(int j = 0; j < matrixColSize[i]; j++) 8 { 9 matrix_new[j][matrixSize - i - 1] = matrix[i][j]; 10 } 11 } 12 13 for(int i = 0; i < matrixSize; i++) 14 { 15 for(int j = 0; j < matrixColSize[i]; j++) 16 { 17 matrix[i][j] = matrix_new[i][j]; 18 } 19 } 20 }
原地旋转:
例如:1 2 3
4 5 6
7 8 9
先转置:1 4 7
2 5 8
3 6 9
然后按照列以中心为轴两边值交换:
7 4 1
8 5 2
9 6 3
这里学到了矩阵的原地转置:
1 for (int i = 0; i < 2; i++) 2 { 3 for (int j = 1; j < 3; j++) 4 { 5 int temp = a[i][j]; 6 a[i][j] = a[j][i]; 7 a[j][i] = temp; 8 9 } 10 }
题目代码:
1 void rotate(int** matrix, int matrixSize, int* matrixColSize) 2 { 3 for(int i = 0; i < matrixSize-1; i++) 4 { 5 for(int j = i+1; j < matrixSize; j++) 6 { 7 int temp = matrix[i][j]; 8 matrix[i][j] = matrix[j][i]; 9 matrix[j][i] = temp; 10 } 11 } 12 13 int mid = matrixSize/2; 14 for(int i = 0; i < matrixSize; i++) 15 { 16 for(int j = 0; j < mid; j++) 17 { 18 int temp = matrix[i][j]; 19 matrix[i][j] = matrix[i][matrixSize-1-j]; 20 matrix[i][matrixSize-1-j] = temp; 21 } 22 } 23 }