您的位置:首页 > 编程语言 > Python开发

leetcode 【 Rotate Image 】python 实现

2015-01-18 23:10 141 查看
题目

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

代码:oj测试通过 Runtime: 53 ms

class Solution:
# @param matrix, a list of lists of integers
# @return a list of lists of integers
def rotate(self, matrix):
if matrix is None:
return None
if len(matrix[0]) < 2 :
return matrix

N = len(matrix[0])

for i in range(0, N/2, 1):
for j in range(i, N-i-1, 1):
ori_row = i
ori_col = j
row = ori_row
col = ori_col
for times in range(3):
new_row = col
new_col = N-row-1
matrix[ori_row][ori_col],matrix[new_row][new_col] = matrix[new_row][new_col],matrix[ori_row][ori_col]
row = new_row
col = new_col
return matrix


思路:

题意是将一个矩阵顺时针旋转90°

小白的解决方法是由外层向里层逐层旋转;每层能够组成正方形对角线的四个元素依次窜一个位置(a b c d 变成 d a b c)。

四个元素转换位置的时候用到一个数组操作的技巧,每次都要第一个位置的元素当成tmp,交换第一个位置的元素与指针所指元素的位置。

原始:a b c d

第一次交换:b a c d

第二次交换:c a b d

第三次交换:d a b c

这样的好处是代码简洁一些 思路比较连贯

Tips:

每层循环的边界条件一定要考虑清楚,小白一开始最外层循环的上届一直写成了N,导致一直不通过,实在是太低级的错误。以后还要加强代码的熟练度,避免出现这样的低级判断错误。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: