[LeetCode]题解(python):048-Rotate Image


题目来源


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)


 1 _author_ = "YE"
 2 # -*- coding:utf-8 -*-
 3 
 4 class Solution(object):
 5     def rotate(self, matrix):
 6         """
 7         :type matrix: List[List[int]]
 8         :rtype: void Do not return anything, modify matrix in-place instead.
 9         """
10         n = len(matrix)
11         for i in range(n):
12             for j in range(i + 1, n):
13                 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
14 
15         for i in range(n):
16             matrix[i].reverse()
17 
18 s = Solution()
19 f = [[1,2,3],
20     [4,5,6],
21     [7,8,9]]
22 
23 print(s.rotate(f))
24 print(f)

 

posted @ 2015-12-16 18:28  loadofleaf  Views(228)  Comments(0Edit  收藏  举报