leetcode 48 Rotate Image

'''
leetcode 48   Rotate Image
给定n*n的二维图像,代表一张图像,将原始图像顺时针旋转90度
必须是in-place的操作,不允许额外分配内存空间再旋转二维数组

给定输入矩阵:
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],
希望输出
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

算法1:
首先对原始的二维矩阵进行转置,得到
[
  [1,4,7],
  [2,5,8],
  [3,6,9]
]
即交换二维数组中的元素,swap(array[i][j],array[j][i])
再交换转置数组每列的元素
但是这样带来的时间复杂度是O(n**2)
'''
class Solution:
    def rotate(self, matrix) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        row=len(matrix)#求出矩阵的行数
        col=len(matrix[0])# 求出矩阵的列数
        # print(matrix)
        for i in range(row):
            for j in range(i+1,col):
                temp=matrix[i][j]
                print(i,j,matrix[i][j])
                matrix[i][j]=matrix[j][i]
                matrix[j][i]=temp
        new_row=len(matrix)
        new_col=len(matrix[0])
        for i in range(row):
            for j in range(new_col//2):
                temp=matrix[i][j]
                matrix[i][j]=matrix[i][new_col-j-1]
                matrix[i][new_col - j - 1]=temp
        # print(matrix)

if __name__=="__main__":
    matrix=[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
]
    Solution().rotate(matrix)
'''
算法2:
每次改变的是二维矩阵中最外面一圈的元素数值,由于顺时针旋转90度实际上只是对于每一层的元素数值存在交换操作
而层与层之间的元素数值并没有交换,故而设定4个指针,用于记录当前所处层的位置
比如对于4*4的矩阵,初始时,四个哨兵的数值分别为:
top=0   left=0  right=col  bottom=row
首先对最外面一层的元素进行交换

'''
class Solution:
    def rotate(self, matrix) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        n=len(matrix)
        top=0
        left=0
        bottom=n-1
        right=n-1
        while(bottom-top>0):
            for i in range(top,bottom):
                temp=matrix[i][right]
                matrix[i][right]=matrix[top][i]
                matrix[top][i]=matrix[n-i-1][left]
                matrix[n - i - 1][left]=matrix[bottom][n-i-1]
                matrix[bottom][n - i - 1]=temp
            bottom-=1
            right-=1
            top+=1
            left+=1
        # print('here',matrix)

if __name__=="__main__":
    matrix=[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
]
    Solution().rotate(matrix)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值