[Leetcode] Template to rotate matrix

 

Rotate the image by 90 degrees (clockwise).

Given input matrix = 
[
  [1,2,3,4],
  [5,6,7,8],
  [9,10,11,12]]
],

rotate the input matrix in-place such that it becomes:
[
  [9,5,1],
  [10,6,2],
  [11,7,3]
[12,8,4] ]

[[1,2,3,4],        [[9,10,11,12],                   [[9,5,1],
[5,6,7,8],  ==>          [5,6,7,8],         ==>          [10,6,2],
[9,10,11,12]]                 [1,2,3,4]]                          [11,7,3],
                      [12,8,4]]

 

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

 

Rotate the image by 90 degrees (anti-clockwise).

Given input matrix = 
[
  [1,2,3,4],
  [5,6,7,8],
  [9,10,11,12]]
],

rotate the input matrix in-place such that it becomes:
[
  [4,8,12],
  [3,7,11],
  [2,6,10]
[1,5,9] ]

[[1,2,3,4],        [[1,5,9],                    [[4,8,12],
[5,6,7,8],  ==>          [2,6,10],         ==>          [3,7,11],
[9,10,11,12]]                  [3,7,11],                         [2,6,10],
            [4,8,12]]         [1,5,9]]

 

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

 

如果matrix是n*n的, 然后需要in-place改的话.可以用以下的模板.

/*
 * clockwise rotate
 * first reverse up to down, then swap the symmetry 
 * 1 2 3     7 8 9     7 4 1
 * 4 5 6  => 4 5 6  => 8 5 2
 * 7 8 9     1 2 3     9 6 3
*/


1      matrix[:] = matrix[::-1] # 记住要用matrix[:], 不然更改的不对
2         #matrix = matrix[::-1]
3         for i in range(len(matrix)):
4             for j in range(i+1, len(matrix)):
5                 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

 

/*
 * anticlockwise rotate
 * first reverse left to right, then swap the symmetry
 * 1 2 3     3 2 1     3 6 9
 * 4 5 6  => 6 5 4  => 2 5 8
 * 7 8 9     9 8 7     1 4 7
*/
1       matrix[:] = [each[::-1] for each in matrix]
3       for i in range(len(matrix)):
4             for j in range(i+1, len(matrix)):
5                 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9194662.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值