diff --git a/0054_spiral-matrix/README.md b/0054_spiral-matrix/README.md new file mode 100644 index 0000000..9f31ff2 --- /dev/null +++ b/0054_spiral-matrix/README.md @@ -0,0 +1,20 @@ +Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. + +Example 1: + +![](https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg) + + Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,3,6,9,8,7,4,5] + +Example 2: + +![](https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg) + + 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` diff --git a/0054_spiral-matrix/python3/solution.py b/0054_spiral-matrix/python3/solution.py new file mode 100644 index 0000000..876b4d4 --- /dev/null +++ b/0054_spiral-matrix/python3/solution.py @@ -0,0 +1,41 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + row_begin_loc, row_end_loc = 0, len(matrix) - 1 + col_begin_loc, col_end_loc = 0, len(matrix[0]) - 1 + result = [] + + while row_begin_loc <= row_end_loc and col_begin_loc <= col_end_loc: + # Top Side + i, j = row_begin_loc, col_begin_loc + while j <= col_end_loc: + result.append(matrix[i][j]) + j += 1 + + # Right Side + i += 1 + j -= 1 + while i <= row_end_loc: + result.append(matrix[i][j]) + i += 1 + + # Bottom Side + i -= 1 + j -= 1 + while j >= col_begin_loc and i > row_begin_loc: + result.append(matrix[i][j]) + j -= 1 + + # Left Side + i -= 1 + j += 1 + while i > row_begin_loc and j < col_end_loc: + result.append(matrix[i][j]) + i -= 1 + + row_begin_loc += 1 + row_end_loc -= 1 + col_begin_loc += 1 + col_end_loc -= 1 + + return result + \ No newline at end of file