Rotate Image

问题:给定一个N x N的数组,将数组元素顺时针旋转90度,并且要求不使用另外的数组

示例:

输入:

matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

 matrix变为:

[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

 matrix变为:

[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]


解决思路:

  # 根据n的大小,确定需要旋转多少个轮次
  # 每个轮次,将所有会旋转的点按照旋转的路径(菱形)划分为多个组,每个组中的元素个数为n
  # 先旋转端点,再旋转其他组,直到下一个端点前停下

Python代码:

class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        if not n:
            return
        num = n // 2
        for i in range(num):
            j = i
            bound = n - i - 1
            while j < bound:
                last = n- j -1
                matrix[j][i],matrix[i][last],matrix[last][bound],matrix[bound][j] = matrix[bound][j],matrix[j][i],matrix[i][last],matrix[last][bound] 
                j += 1

 

posted @ 2019-05-25 11:34  秦qin  阅读(129)  评论(0编辑  收藏  举报