首页 > 编程语言 > 详细

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

时间:2015-12-16 19:36:10      阅读:229      评论:0      收藏:0      [点我收藏+]

题目来源


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)

 

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

原文:http://www.cnblogs.com/loadofleaf/p/5052011.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!