Cracking the Coding Interview-1.7

第六版Cracking the Coding Interview题目1.7,题目如下:

Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

题目是顺时针90度旋转矩阵,若使用numpy可直接调用numpy.rot90(matrix,3),若不使用numpy,则直接按要求调换元素位置如下:

def rotatemMatrix(matrix):
    n = len(matrix)
    for layer in xrange(n / 2):
        first, last = layer, n - layer - 1
        for i in xrange(first, last):
            # save top
            top = matrix[layer][i]
            # left -> top
            matrix[layer][i] = matrix[-i - 1][layer]
            # bottom -> left
            matrix[-i - 1][layer] = matrix[-layer - 1][-i - 1]
            # right -> bottom
            matrix[-layer - 1][-i - 1] = matrix[i][- layer - 1]
            # top -> right
            matrix[i][- layer - 1] = top
    return matrix

在手机上阅读或分享本文请扫描以下二维码:
By @Zhengyi Yang in
Tags : #cracking the coding interview, #python, #matrix,

Comments

评论功能已关闭。