|
| 1 | +class Solution: |
| 2 | + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: |
| 3 | + |
| 4 | + res = [] # This will store the elements in spiral order |
| 5 | + left, right = 0, len(matrix[0]) # Initialize left and right pointers for columns |
| 6 | + top, bottom = 0, len(matrix) # Initialize top and bottom pointers for rows |
| 7 | + |
| 8 | + # Loop until the pointers cross each other |
| 9 | + while left < right and top < bottom: |
| 10 | + |
| 11 | + # Traverse from left to right on the top row |
| 12 | + for i in range(left, right): |
| 13 | + res.append(matrix[top][i]) |
| 14 | + top += 1 # Move the top boundary down |
| 15 | + |
| 16 | + # Traverse from top to bottom on the rightmost column |
| 17 | + for i in range(top, bottom): |
| 18 | + res.append(matrix[i][right - 1]) |
| 19 | + right -= 1 # Move the right boundary left |
| 20 | + |
| 21 | + # Check if we are still within valid boundaries after moving top and right |
| 22 | + if not (left < right and top < bottom): |
| 23 | + break # If the matrix is fully traversed, exit the loop |
| 24 | + |
| 25 | + # Traverse from right to left on the bottom row |
| 26 | + for i in range(right - 1, left - 1, -1): |
| 27 | + res.append(matrix[bottom - 1][i]) |
| 28 | + bottom -= 1 # Move the bottom boundary up |
| 29 | + |
| 30 | + # Traverse from bottom to top on the leftmost column |
| 31 | + for i in range(bottom - 1, top - 1, -1): |
| 32 | + res.append(matrix[i][left]) |
| 33 | + left += 1 # Move the left boundary right |
| 34 | + |
| 35 | + return res # Return the spiral order traversal |
0 commit comments