Rotate Image
LeetCode 48 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Transpose, then mirror each row.
నేను Rotate Image (LeetCode 48) ను ఇలా పరిష్కరించాను — Matrix ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
A 90° clockwise rotation equals a transpose (swap across the main diagonal) followed by reversing each row. Both steps are in-place swaps.
Approach
- 1
Swap matrix[i][j] with matrix[j][i] for j ≥ i.
- 2
Reverse every row by swapping its ends inward.
నేను ఎలా పరిష్కరించాను
Transpose + reflectPythonO(n²) time · O(1) space
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
"""
#transpose
[1][4][7]
[2][5][8]
[3][6][9]
#reflect
[7][4][1]
[8][5][2]
[9][6][3]
"""
m = len(matrix)
n = len(matrix[0])
for i in range(m):
for j in range(i,n):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
for i in range(m):
for j in range(n//2):
matrix[i][j],matrix[i][n-j-1]=matrix[i][n-j-1],matrix[i][j]
Rotate Image — తరచూ అడిగే ప్రశ్నలు
Rotate Image వెనుక ఉన్న intuition ఏమిటి?
A 90° clockwise rotation equals a transpose (swap across the main diagonal) followed by reversing each row. Both steps are in-place swaps.
Rotate Image (LeetCode 48) ను ఎలా పరిష్కరించాలి?
1. Swap matrix[i][j] with matrix[j][i] for j ≥ i. 2. Reverse every row by swapping its ends inward.
Rotate Image యొక్క time, space complexity ఎంత?
Time: O(n²). Space: O(1). (Accepted approach: Transpose + reflect.)
Rotate Image లో సాధారణ పొరపాట్లు ఏమిటి?
Start the transpose inner loop at j = i, or every pair is swapped twice (back to the original).