I came across a problem on Leetcode that asks to rotate an image 90 degree clockwise as shown below (image credit: Leetcode)
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!