旋转图像

旋转图像

题目说明

给定一个 n×n 的二维矩阵表示一个图像。

将图像顺时针旋转90度。

你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

示例 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

示例 2:

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

原地旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

解决方案

  1. 先变换最外层,逐渐向内深入,同时旋转90度。具体实现方式如下:

方案一

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
length = len(matrix)
for i in range(length):
for j in range(i+1, length):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for i in range(length):
matrix[i] = matrix[i][::-1]

方案二

1
matrix[:] = map(list, zip(*matrix[::-1]))

注:

  • Map

    map(function, iterable, …)

    Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function isNone, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation).
    The iterable arguments may be a sequence or any iterable object; the result is always a list.

  • zip

    zip(seq1 [, seq2 […]]) -> [(seq1[0], seq2[0] …), (…)]

    Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence.

    总之,zip([seql, …])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    >>> zip_test = zip(*[[1,2,3],[4,5,6],[7,8,9]])
    >>> test1 = []
    >>> while 1:
    try:
    val = next(zip_test)
    # print(val)
    test1.append(val)
    except StopIteration:
    break

    >>> test1
    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    >>> map_test = map(list,zip(*[[1,2,3],[4,5,6],[7,8,9]]))
    >>> test2 = []
    >>> while 1:
    try:
    val = next(map_test)
    # print(val)
    test2.append(val)
    except StopIteration:
    break
    >>> test2
    [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

    矩阵的顺时针旋转:先把矩阵上下翻转,然后在转置一下

    1
    matrix[:] = map(list, zip(*matrix[::-1]))

    矩阵的逆时针旋转:先把矩阵转置一下,然后在上下翻转:

    1
    matrix[:] = map(list, zip(*matrix))[::-1]

说明: 如果您有更好的解决方案或者本人写的有什么问题,请多多指教!