+ 1

Rotate Image - Solution Explanation

Problem: You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. Constraints: -| matrix.length == n -| matrix[i].length == n -| 1 <= n <= 20 -| -1000 <= matrix[i][j] <= 1000 After a bit of research, I found a number of solutions to the problem, and each of them worked when I submitted them. This solution seemed the most "efficient": class Solution: def rotate(self, matrix: List[List[int]]) -> None: for i in range(0,len(matrix)//2): temp = matrix[i] matrix[i] = matrix[len(matrix)-1-i] matrix[len(matrix)-1-i] = temp for i in range(len(matrix)): for j in range(i+1,len(matrix)): temp = matrix[i][j] matrix[i][j] = matrix[j][i] matrix[j][i] = temp If possible, I'd just like someone to explain to me what's happening line by line. Kind of work backwards to understand the logic behind the code. Having the right answer is nice, but it's useless if I don't understand WHY it's doing what it's doing.

13th Sep 2020, 11:05 PM
deepspaceghost
deepspaceghost - avatar
0 Respuestas