0% found this document useful (0 votes)
7 views1 page

Rotate Image Matrix Solution

This Python code rotates a matrix 90 degrees clockwise by swapping elements. It iterates through the matrix starting from the top left, saves the top left element, and swaps it with the bottom left, bottom right, top right, and top left elements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Rotate Image Matrix Solution

This Python code rotates a matrix 90 degrees clockwise by swapping elements. It iterates through the matrix starting from the top left, saves the top left element, and swaps it with the bottom left, bottom right, top right, and top left elements.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

48.

Rotate Image
class Solution(object):
def rotate(self, matrix):

l, r = 0, len(matrix) - 1
while l < r:
for i in range(r - l):
top, bottom = l, r

# save the topleft


topLeft = matrix[top][l + i]

# move bottom left into top left


matrix[top][l + i] = matrix[bottom - i][l]

# move bottom right into bottom left


matrix[bottom - i][l] = matrix[bottom][r - i]

# move top right into bottom right


matrix[bottom][r - i] = matrix[top + i][r]

# move top left into top right


matrix[top + i][r] = topLeft
r -= 1
l += 1

You might also like