在leetcode的48题中
,考察了旋转 π 2 \frac{\pi}{2} 2π角度之后,如何拆解成基本的轴操作进行替换,其实可以理解成欧拉角相关的,但是对于本题而言,用欧拉角确实有点大材小用,简单的二维矩阵即可做一些简单的拆解,通过相关的基本操作,可以得到一些列的操作,在后续题目中可以通过这些操作进行各个角度的变换,但是毫无疑问,这里肯定是不会考察很复杂的操作了
第一个,按照 x轴对称,相应的计算矩阵
σ
x
(
π
)
=
(
1
0
0
−
1
)
\sigma_x(\pi) = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} \quad
σx(π)=(100−1)
考察关于x轴对称的变化
(
x
y
)
→
(
x
−
y
)
\begin{pmatrix} x \\ y \end{pmatrix} \rightarrow \quad \begin{pmatrix} x \\ -y \end{pmatrix}
(xy)→(x−y)
即可得到上述的变化矩阵,
相应的Java实现代码为
public static int[][] reverseMatrix(int[][] nums){
if (nums.length != nums[0].length)
return null;
int n = nums.length;
// int m = n/2;
for (int i = 0; i < n/2; i++){
for(int j = 0; j < n;j++){
int temp = nums[i][j];
nums[i][j] = nums[n-i-1][j];
nums[n-i-1][j] = temp;
}
}
return nums;
}
关于y = x对称的操作,即反对角线的对称
(
x
y
)
→
(
y
x
)
\begin{pmatrix} x \\ y \end{pmatrix} \rightarrow \quad \begin{pmatrix} y \\ x \end{pmatrix}
(xy)→(yx)
public static int[][] croDigReverse(int[][] nums){
if (nums.length != nums[0].length)
return null;
int n = nums.length;
for (int i = 0; i < n; i++){
for (int j = 0; j < n-i;j++){
int temp = nums[i][j];
nums[i][j] = nums[n - 1 -j][n - 1 -i];
nums[n - 1 -j][n - 1 -i] = temp;
}
}
return nums;
}
而对于y = -x对称即关于矩阵的对角线对称操作,则对应的矩阵是
θ
y
=
−
x
=
(
0
−
1
−
1
0
)
\theta_{y =-x} = \begin{pmatrix} 0 & -1 \\ -1 & 0 \end{pmatrix} \quad
θy=−x=(0−1−10)
对应的映射关系是
(
x
y
)
→
(
−
y
−
x
)
\begin{pmatrix} x \\ y \end{pmatrix} \rightarrow \quad \begin{pmatrix} -y \\ -x \end{pmatrix}
(xy)→(−y−x)
相应的Java代码为
public static int[][] dignalReverseMatrix(int[][] nums){
// 检查是否为方阵
if (nums.length != nums[0].length)
return null;
int n = nums.length;
for (int i = 0; i < n;i++){
for (int j = 0; j < i; j++) {
int temp = nums[i][j];
nums[i][j] = nums[j][i];
nums[j][i] = temp;
}
}
return nums;
}
在上述基础变化之后,本题就变得容易了,不难发现该操作
θ
z
(
π
2
)
=
(
0
1
−
1
0
)
\theta_{z}(\frac{\pi}{2}) = \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} \quad
θz(2π)=(0−110)
满足关系
θ
z
(
π
2
)
=
θ
y
=
−
x
⋅
σ
x
(
π
)
\theta_{z}(\frac{\pi}{2}) =\theta_{y =-x} \cdot \sigma_x(\pi) \quad
θz(2π)=θy=−x⋅σx(π)
即先进行
σ
x
(
π
)
\sigma_x(\pi)
σx(π) 操作之后,再进行
θ
y
=
−
x
\theta_{y =-x}
θy=−x操作,即等效于的是
θ
z
(
π
2
)
\theta_{z}(\frac{\pi}{2})
θz(2π),因此最终的实现代码即是
class Solution {
public void rotate(int[][] matrix) {
dignalReverseMatrix(reverseMatrix(matrix));
}
public int[][] reverseMatrix(int[][] nums){
int n = nums.length;
// int m = n/2;
for (int i = 0; i < n/2; i++){
for(int j = 0; j < n;j++){
int temp = nums[i][j];
nums[i][j] = nums[n-i-1][j];
nums[n-i-1][j] = temp;
}
}
return nums;
}
public void dignalReverseMatrix(int[][] nums){
// 检查是否为方阵
int n = nums.length;
for (int i = 0; i < n;i++){
for (int j = 0; j < i; j++) {
int temp = nums[i][j];
nums[i][j] = nums[j][i];
nums[j][i] = temp;
}
}
// return nums;
}
}