[LeetCode]题解(python):054-Spiral Matrix
题目来源
https://leetcode.com/problems/spiral-matrix/
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
题意分析
Input: a matrix
Output: a list
Conditions: 蛇形输出
题目思路
自己本来在想有没有一些不一样的算法,然后发现直接右下左上顺序做就好了,看到一个博客的分类做得不错,重点是要看边界情况,直接看代码。
AC代码(Python)
1 class Solution(object): 2 def spiralOrder(self, matrix): 3 """ 4 :type matrix: List[List[int]] 5 :rtype: List[int] 6 """ 7 if matrix == []: 8 return [] 9 up = 0 10 left = 0 11 down = len(matrix) - 1 12 right = len(matrix[0]) - 1 13 14 direct = 0 15 16 res = [] 17 18 while True: 19 if direct == 0: 20 for i in range(left, right + 1): 21 res.append(matrix[up][i]) 22 up += 1 23 if direct == 1: 24 for i in range(up, down + 1): 25 res.append(matrix[i][right]) 26 right -= 1 27 if direct == 2: 28 for i in range(right, left - 1, -1): 29 res.append(matrix[down][i]) 30 down -= 1 31 if direct == 3: 32 for i in range(down, up -1, -1): 33 res.append(matrix[i][left]) 34 left += 1 35 if up > down or left > right: 36 return res 37 direct = (direct + 1) % 4 38 39