Given an m x n
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.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: ROWS, COLS = len(matrix), len(matrix[0]) top, left = 0, 0 right, bottom = COLS, ROWS res = [] while left < right and top < bottom: # get every i in top row for i in range(left, right): res.append(matrix[top][i]) top += 1 # get every i in right column for i in range(top, bottom): res.append(matrix[i][right - 1]) right -= 1 if not (top < bottom and left < right): break # get every i in bottom row for i in range(right - 1, left - 1, -1): res.append(matrix[bottom - 1][i]) bottom -= 1 # get every i in left col for i in range(bottom - 1, top - 1, -1): res.append(matrix[i][left]) left += 1 return res
This article is contributed by Ashwini Verma. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.