| Operation | Logic | Python Code Implementation |
|---|---|---|
| Diagonal Flip (Transpose) | Swap row/col across the main diagonal. | for i in range(n): for j in range(i + 1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] |
| Horizontal Axis Flip (Vertical Reflection) | Swap entire rows from top to bottom. | for i in range(n // 2): matrix[i], matrix[n-1-i] = matrix[n-1-i], matrix[i] |
| Vertical Axis Flip (Horizontal Reflection) | Swap columns within each row from left to right. | for i in range(n): for j in range(n // 2): matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j] |
To rotate a matrix in-place, perform these fundamental flips in sequence:
- 90° Clockwise:
- Diagonal Flip (Transpose)
- Vertical Axis Flip (Horizontal Reflection)
- 180° Rotation:
- Horizontal Axis Flip (Vertical Reflection)
- Vertical Axis Flip (Horizontal Reflection)
- 270° Clockwise (or 90° Counter-Clockwise):
- Diagonal Flip (Transpose)
- Horizontal Axis Flip (Vertical Reflection)
Essential for all reflection operations. Since you are swapping two elements at once, you only need to visit half the length. If you iterate through the full length, you perform a "double-swap," which returns the matrix to its original state.
This mathematical formula finds the element's partner on the opposite side of the axis. The sum of an index and its mirror partner always equals the maximum index (
- When
$j = 0$ , partner is$n - 1$ . - When
$j = 1$ , partner is$n - 2$ .
In a diagonal flip, starting the inner loop at i + 1 ensures you skip the elements on the diagonal (which don't move) and only visit the "upper triangle." This prevents redundant swaps that would undo the transposition.
If a problem asks to flip over the line from the top-right to bottom-left:
-
Formula:
matrix[i][j]$\leftrightarrow$ matrix[n - 1 - j][n - 1 - i]
Reference for Coding Interviews & Algorithm Design