Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
Given an mxn matrix, return all elements of the matrix in spiral order.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 10-100 <= matrix[i][j] <= 100
内容目录
TogglePython
# time complexity: O(m*n) # space complexity: O(1) from typing import List class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: ROW = len (matrix) COL = len(matrix[0]) direction = 1 row = 0 col = -1 result = [] while ROW > 0 and COL > 0: for _ in range(COL): col += direction result.append (matrix[row][col]) ROW -= 1 for _ in range(ROW): row += direction result.append(matrix[row][col]) COL -= 1 direction *= -1 return result matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(Solution().spiralOrder(matrix)) matrix = [[1, 2, 3, 4], [ 5, 6, 7, 8], [9, 10, 11, 12]] print(Solution().spiralOrder(matrix))



![[LeetCode] 0123. Best Time to Buy and Sell Stock III](https://hogantechs.com/wp-content/uploads/2024/11/1-1024x577.avif)