码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode]题解(python):054-Spiral Matrix

时间:2015-12-28 16:54:00      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:


题目来源


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                     

 

[LeetCode]题解(python):054-Spiral Matrix

标签:

原文地址:http://www.cnblogs.com/loadofleaf/p/5082952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!