LeetCode Spiral Matrix
Spiral Matrix for solving LeetCode Problems
Original question
Returns the content of a matrix in a spiral output.
Note:
The matrix is not necessarily a square.
Example:
Input: matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
Solutions
Controls the border of the current traversal and inner indentation. Note that the following situations may occur when you scale down to the innermost part:
There is a value left in the center --- | 3 | --- multiple values in the center horizontal --------- | 3 4 5 6 | --------- multiple values in the center vertical --- | 2 | 3 | 4 | ---
Just process them separately.
AC Source Code
class Solution(object): def spiralOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if not matrix: return [] left = top = 0 right = len(matrix[0]) - 1 bottom = len(matrix) - 1 result = [] while left < right and top < bottom: for i in range(left, right): result.append(matrix[top][i]) for i in range(top, bottom): result.append(matrix[i][right]) for i in range(right, left, -1): result.append(matrix[bottom][i]) for i in range(bottom, top, -1): result.append(matrix[i][left]) left += 1 right -= 1 top += 1 bottom -= 1 if left == right and top == bottom: result.append(matrix[top][left]) elif left == right: for i in range(top, bottom + 1): result.append(matrix[i][left]) elif top == bottom: for i in range(left, right + 1): result.append(matrix[top][i]) return resultif __name__ == "__main__": assert Solution().spiralOrder([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) == [1, 2, 3, 6, 9, 8, 7, 4, 5] assert Solution().spiralOrder([[2], [3]]) == [2, 3] assert Solution().spiralOrder([[2, 3]]) == [2, 3]