题目
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
题意
给定一个矩阵,在该矩阵上顺时针旋转元素
例子
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
题解
可以先对矩阵进行转置,第n行转为第n列
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
转置后
[
[ 5, 2, 13,15],
[ 1, 4, 3,14],
[9, 8, 6,12],
[11,10,7,16]
],
然后再每一行i 与 N-i交换位置即可得到(即逆序)。
[
[ 15, 13, 2,5],
[ 14, 3, 4,1],
[12, 6, 8,9],
[16,7,10,11]
],
代码
func rotate(matrix [][]int) {
N := len(matrix)
if N==0{
return
}
for i:=0;i<N;i++{
for j:=i+1;j<N;j++{
temp := matrix[i][j]
matrix[i][j]=matrix[j][i]
matrix[j][i]=temp
}
left:=0;
right:=N-1;
for left<right{
temp:=matrix[i][left]
matrix[i][left]=matrix[i][right]
matrix[i][right]=temp
left++
right--
}
}
}
总结
需要对矩阵的变化有一定了解。矩阵这东西,有时候可以从左上角或者右上角以及所在的行列去解决局部问题,然后逐渐缩小范围。