Spiral Matrix
LeetCode 54 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Four shrinking boundaries; guard the bottom and left passes.
ನಾನು Spiral Matrix (LeetCode 54) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Matrix ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Peel the matrix layer by layer with four boundaries. Walk the top row, the right column, the bottom row backwards and the left column upwards, shrinking each boundary after you use it.
Approach
- 1
top, bottom, left, right define the unvisited rectangle.
- 2
Left→right along top, then top++.
- 3
Top→bottom along right, then right−−.
- 4
If rows remain, right→left along bottom; if columns remain, bottom→top along left.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Boundary simulationPythonO(m·n) time
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
#4 pointers, top, right, bottom, left
#move from left to right
#move from top to bottom
#move from right to left - handle single row
#move from bottom to top - handle single col
m = len(matrix)
n = len(matrix[0])
top=0
bottom = m-1
left = 0
right = n-1
res=[]
while top<=bottom and left<=right:
for i in range(left,right+1):
res.append(matrix[top][i])
top+=1
for i in range(top,bottom+1):
res.append(matrix[i][right])
right-=1
if top<=bottom:
for j in range(right,left-1,-1):
res.append(matrix[bottom][j])
bottom-=1
if left<=right:
for i in range(bottom,top-1,-1):
res.append(matrix[i][left])
left+=1
return res Spiral Matrix — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Spiral Matrix ಹಿಂದಿನ intuition ಏನು?
Peel the matrix layer by layer with four boundaries. Walk the top row, the right column, the bottom row backwards and the left column upwards, shrinking each boundary after you use it.
Spiral Matrix (LeetCode 54) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. top, bottom, left, right define the unvisited rectangle. 2. Left→right along top, then top++. 3. Top→bottom along right, then right−−. 4. If rows remain, right→left along bottom; if columns remain, bottom→top along left.
Spiral Matrix ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(m·n). Space: O(1) extra. (Accepted approach: Boundary simulation.)
Spiral Matrix ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Without the top ≤ bottom and left ≤ right checks, a single remaining row or column is read twice.