题目来源
https://leetcode.com/problems/rotate-image/
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
题意分析
Input:a matrix represented with list[list[]]
Output:a matrix
Conditions:rotate 90 degrees clockwise
题目思路
注意到是将原来的矩阵顺时针旋转90度,本来直接转换比较费劲,网上大神说先转置然后每一行reverse即得所求,仔细观察矩阵的构造,的确如此,代码就几行……注意观察,不一定要一步得出答案。
AC代码(Python)
_author_ = "YE"
# -*- coding:utf-8 -*- class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for i in range(n):
matrix[i].reverse() s = Solution()
f = [[1,2,3],
[4,5,6],
[7,8,9]] print(s.rotate(f))
print(f)