|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# @Time : 2019/3/15 18:42 |
| 3 | +# @Author : xulzee |
| 4 | + |
| 5 | +# @File : 54. Spiral Matrix.py |
| 6 | +# @Software: PyCharm |
| 7 | +from typing import List |
| 8 | + |
| 9 | + |
| 10 | +class Solution: |
| 11 | + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: |
| 12 | + if matrix == []: |
| 13 | + return [] |
| 14 | + start_row, start_column = 0, 0 |
| 15 | + end_row, end_column = len(matrix) - 1, len(matrix[0]) - 1 |
| 16 | + res = [] |
| 17 | + while start_column <= end_column and start_row <= end_row: |
| 18 | + self.printEdge(matrix, start_row, start_column, end_row, end_column, res) |
| 19 | + start_column += 1 |
| 20 | + start_row += 1 |
| 21 | + end_column -= 1 |
| 22 | + end_row -= 1 |
| 23 | + return res |
| 24 | + |
| 25 | + def printEdge(self, matrix: list, start_row: int, start_column: int, end_row: int, end_column: int, res: List): |
| 26 | + if start_row == end_row: |
| 27 | + while start_column <= end_column: |
| 28 | + res.append(matrix[start_row][start_column]) |
| 29 | + start_column += 1 |
| 30 | + elif start_column == end_column: |
| 31 | + while start_row <= end_row: |
| 32 | + res.append(matrix[start_row][start_column]) |
| 33 | + start_row += 1 |
| 34 | + else: |
| 35 | + cur_row = start_row |
| 36 | + cur_column = start_column |
| 37 | + while cur_column < end_column: |
| 38 | + res.append(matrix[cur_row][cur_column]) |
| 39 | + cur_column += 1 |
| 40 | + while cur_row < end_row: |
| 41 | + res.append(matrix[cur_row][cur_column]) |
| 42 | + cur_row += 1 |
| 43 | + while cur_column > start_column: |
| 44 | + res.append(matrix[cur_row][cur_column]) |
| 45 | + cur_column -= 1 |
| 46 | + while cur_row > start_row: |
| 47 | + res.append(matrix[cur_row][cur_column]) |
| 48 | + cur_row -= 1 |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == '__main__': |
| 52 | + # A = [[5, 1, 9, 11], |
| 53 | + # [2, 4, 8, 10], |
| 54 | + # [13, 3, 6, 7], |
| 55 | + # [15, 14, 12, 16]] |
| 56 | + A = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]] |
| 57 | + res = [] |
| 58 | + res = Solution().spiralOrder(A) |
| 59 | + print(res) |
0 commit comments