0

I came across a problem on Leetcode that asks to rotate an image 90 degree clockwise as shown below (image credit: Leetcode)

enter image description here

One of the solutions provided is as follows:

class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
    self.transpose(matrix)
    self.reflect(matrix)

def transpose(self, matrix):
    n = len(matrix)
    for i in range(n):
        for j in range(i + 1, n):
            # Does the assignment here happen simultaneously?
            matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]

def reflect(self, matrix):
    n = len(matrix)
    for i in range(n):
        for j in range(n // 2):
            matrix[i][j], matrix[i][-j - 1] = matrix[i][-j - 1], matrix[i][j]

The solution is to first transpose the original matrix along the diagonal line and then reverse it along the X axis. That results in 90-degree clockwise rotation.

What I don't know is this -- I don't think this simultaneously assignment, matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i], will work without the assignment of matrix[j][i]=matrix[i][j] and matrix[i][j]=matrix[j][i] happening at the same time. In other words, if matrix[j][i]=matrix[i][j] were to happen first, then the value in matrix[j][i] would have been changed/tainted before it is assigned to matrix[i][j].

Could someone, who knows more about the behind-the-scene execution of simultaneous assignments, explain me why matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i] is possible without using temp variable?

Thank you in advance for your answers!

user1330974
  • 2,500
  • 5
  • 32
  • 60

1 Answers1

1

No, it's not simultaneous. But the right side is evaluated completely before any assignments take place.

It's essentially equivalent to:

temp = matrix[i][j], matrix[j][i]
matrix[j][i] = temp[0]
matrix[i][j] = temp[1]

temp contains the values in the matrix cells, not references to the matrix cells. So reassigning the matrix elements has no effect on temp.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Thank you! I learned something new about Python today (that is, Python evaluates the right side of the expression first, and that it uses stack in assembly to swap them). – user1330974 Aug 31 '22 at 00:35