简体   繁体   English

旋转图像 - leetcode

[英]Rotate image - leetcode

Apologies if I am asking something stupid (I'm pretty new to coding), but I didn't manage to find a clear explanation to my doubt.如果我问一些愚蠢的问题(我对编码很陌生),我深表歉意,但我没有找到明确的解释来解决我的疑问。 I came across the following problem on leetcode:我在 leetcode 上遇到了以下问题:

You are given an nxn 2D matrix representing an image, rotate the image by 90 degrees (clockwise).给定一个表示图像的 nxn 2D 矩阵,将图像旋转 90 度(顺时针)。 You have to rotate the image in-place, which means you have to modify the input 2D matrix directly.您必须就地旋转图像,这意味着您必须直接修改输入的 2D 矩阵。 DO NOT allocate another 2D matrix and do the rotation.不要分配另一个二维矩阵并进行旋转。 Example: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[7,4,1],[8,5,2],[9,6,3]]示例:输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[[7,4,1],[8,5,2], [9,6,3]]

My solution is:我的解决方案是:

class Solution:
    def rotate(self, matrix):
        l = len(matrix)

        clockwise_nums = [matrix[j][i] for i in range(l) for j in range(l - 1, -1, -1)]

        final_array = [clockwise_nums[i:i + l] for i in range(0, len(clockwise_nums), l)]

        return final_array

The sheer execution (matrix rotation) works but this is not accepted as it's not in-place.纯粹的执行(矩阵旋转)有效,但这不被接受,因为它不是就地的。 But I don't really get what that means.但我真的不明白这意味着什么。 Do you think my approach is way off here and I should try something different?你认为我的方法离这里很远,我应该尝试不同的方法吗? Or is there a way to adjust my solution (was quite happy that I came up with a way to rotate the matrix)?或者有没有办法调整我的解决方案(很高兴我想出了一种旋转矩阵的方法)? Also, any tip about in-place algorithm would be much appreciated.此外,任何关于就地算法的提示将不胜感激。 Many thanks!非常感谢!

To understand the difference between "do the operation in-place" and "return a new array", imagine a simpler problem:要理解“就地执行操作”和“返回新数组”之间的区别,请想象一个更简单的问题:

You are given a list.给你一个清单。 Add 1 to every element of the list.将 1 添加到列表的每个元素。

# returning a new array
def add_one_copy(l):
  return [x + 1 for x in l]

# in-place
def add_one_inplace(l):
  for i in range(len(l)):
    l[i] = l[i] + 1

Testing those two functions in the python interactive interpreter highlights the difference:在 python 交互式解释器中测试这两个函数突出了不同之处:

>>> a = [1, 2, 3]
>>> add_one_copy(a)
[2, 3, 4]
>>> a
[1, 2, 3]
>>> add_one_inplace(a)
>>> a
[2, 3, 4]

add_one_copy returns a result, but does not modify a . add_one_copy返回结果,但不a . add_one_inplace does not return a result, but modifies the list. add_one_inplace不返回结果,但会修改列表。 There is the same difference between the python functions sorted and list.sort : python 函数sortedlist.sort之间有相同的区别:

>>> a = [3,4,2,1]
>>> sorted(a)
[1, 2, 3, 4]
>>> a
[3, 4, 2, 1]
>>> a.sort()
>>> a
[1, 2, 3, 4]

sorted returns a result, but does not modify the list. sorted返回结果,但不修改列表。 .sort modifies the list and does not return a result. .sort修改列表并且不返回结果。

Now, the problem you are trying to solve is a little bit more complicated than just adding 1 to every element.现在,您要解决的问题比仅向每个元素添加 1 稍微复杂一些。 The difficulty when solving your rotation problem in-place is that you are moving elements around in the matrix;就地解决旋转问题的困难在于您在矩阵中移动元素; when doing that, you must be careful not to overwrite the values of elements which you still need.这样做时,您必须小心不要覆盖您仍然需要的元素的值。 Imagine a slightly harder problem:想象一个稍微难一点的问题:

You are given a list.给你一个清单。 Reverse the order of the elements in the list.颠倒列表中元素的顺序。

# returning a copy
def reverse_copy(l):
  return [l[len(l) - i - 1] for i in range(len(l))]

# in-place attempt, fall head-first in the trap, this is not working
def reverse_inplace_wrong(l):
  for i in range(len(l)):
    l[i] = l[len(l) - i - 1]

# in-place, correct
def reverse_inplace(l):
  for i in range(len(l)//2):
    tmp = l[len(l) - i - 1]
    l[len(l) - i - 1] = l[i]
    l[i] = tmp

Testing:测试:

>>> a = [1,2,3,4,5,6,7]
>>> reverse_copy(a)
[7, 6, 5, 4, 3, 2, 1]
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> reverse_inplace_wrong(a)
>>> a
[7, 6, 5, 4, 5, 6, 7]
>>> a = [1,2,3,4,5,6,7]
>>> reverse_inplace(a)
>>> a
[7, 6, 5, 4, 3, 2, 1]

When reversing the list, I figured out that element at position i should go to position len(l) - i - 1 .反转列表时,我发现位置i的元素应该转到位置len(l) - i - 1 When rotating the matrix, you have to figure out where the element at position (i,j) should go.旋转矩阵时,您必须弄清楚位置(i,j)处的元素应该去哪里。 And you have to be careful not to repeat the mistake I made in reverse_inplace_wrong .而且你必须小心不要重复我在reverse_inplace_wrong中犯的错误。

For solving this problem we can also use Python built-in reverse() , wouldn't be a deal breaker:为了解决这个问题,我们还可以使用 Python 内置的reverse() ,不会破坏交易:

class Solution:
    def rotate(self, A):
        A.reverse()
        for row in range(len(A)):
            for col in range(row):
                A[row][col], A[col][row] = A[col][row], A[row][col]

If you know C++ you may have a look at my solution.如果你知道 C++,你可以看看我的解决方案。

I solved it using the logic of transpose of a matrix.我使用矩阵转置的逻辑解决了它。 And after transposing, I swapped the first column value with the last column, in the same row.在转置之后,我将第一列的值与同一行中的最后一列交换。 Then the second column with the second last column, and so on.然后第二列与倒数第二列,依此类推。

void swapValues(int &valueOne, int &valueTwo) {
    int tempValue = valueOne;
    valueOne = valueTwo;
    valueTwo = tempValue;
}
    
void rotate(vector<vector<int> >& matrix) {
    int n = matrix.size();
    int halfN = n / 2;

    for (int i=0; i<n; i++) {
        for (int j=0; j<n; j++) {
            if(i != j && j > i) {
                swapValues(matrix[i][j], matrix[j][i]);
            }
        }

        for (int j=0; j<halfN; j++) {
            swapValues(matrix[i][j], matrix[i][n-1-j]);
        }
    }
}
class Solution:
    def rotate(self, matrix):
        rotate_mat = []
        for l in range(len(matrix)):
            mat = [i[l] for i in matrix][::-1]
            rotate_mat.append(mat)
        return rotate_mat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM