48. Rotate Image

给一个二维数组按顺时针旋转九十度

思路:需要熟练,先将矩阵沿着左下到右上的对角线翻转,再上下翻转,就可以实现顺时针旋转90度的效果

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
# 6 star,
# 参考: https://shenjie1993.gitbooks.io/leetcode-python/048%20Rotate%20Image.html
n = len(matrix)
for row in range(n):
for column in range(n - row):
matrix[row][column], matrix[n - 1 - column][n - 1 - row] = matrix[n - 1 - column][n - 1 - row], \
matrix[row][column]
matrix.reverse()

Go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func rotate(matrix [][]int)  {
var tempSlice []int
var temp int
cols := len(matrix)
//rows := len(matrix[0])
for index:=0; index < cols/2; index++ {
tempSlice = matrix[index]
matrix[index] = matrix[cols-1-index]
matrix[cols-1-index] = tempSlice
}
for i:=0; i<cols; i++ {
for j:=0; j< i; j++ {
temp = matrix[i][j]
matrix[i][j] = matrix[j][i]
matrix[j][i] = temp
}
}

}