zoukankan      html  css  js  c++  java
  • [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)
  • 相关阅读:
    [NOIP2008] 传纸条
    [NOIP2006] 能量项链
    [poj2393] Yogurt factory
    [poj3069] Saruman's Army
    [NOIP2011] 观光公交
    [NOIP2010] 关押罪犯
    [洛谷2744] 量取牛奶
    [poj3281] Dining
    关于几类STL容器的swap复杂度问题
    折半法
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5052011.html
Copyright © 2011-2022 走看看