leetcode 将一个二维矩阵进行90度旋转
import numpy as np import math if __name__ == '__main__': def rotate(matrix): n = len(matrix[0]) for i in range(math.ceil((n-1)/2)): for j in range(i,n-i-1): temp = matrix[i][j] matrix[i][j] = matrix[n-1-j][i] matrix[n-1-j][i] = matrix[n-1-i][n-1-j] matrix[n-1-i][n-1-j] = matrix[j][n-1-i] matrix[j][n-1-i] = temp return matrix matrix =np.arange(1,17).reshape(4,4) print(rotate(matrix))
如图3×3的旋转过程:
如图4×4旋转过程: