#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
54: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.
For example,
Given the following matrix:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
You should return [1,2,3,6,9,8,7,4,5].
= = = Comments by dabay===
A lap of treatment, a total of processing N/2 circle.
Pay attention to some details, such as laps, and don't repeat the same lap.
‘‘‘
Class Solution:
# @param Matrix, a list of lists of integers
# @return A list of integers
def spiralorder (self, Matrix):
If Len (matrix) = = 0:
return []
If Len (matrix) = = 1:
return matrix[0]
If Len (matrix[0]) = = 1:
return [i[0] for i in Matrix]
Height = len (matrix)
width = len (matrix[0])
res = []
n = 0
While N < (min (height, width) +1)/2:
For I in Xrange (n, width-n):
Res.append (Matrix[n][i])
For I in Xrange (N+1, height-n):
Res.append (Matrix[i][width-1-n])
If n < height-n-1:
For I in Reversed (Xrange (n, width-n-1)):
Res.append (Matrix[height-n-1][i])
For I in Reversed (xrange (n+1, height-n-1)):
Res.append (Matrix[i][n])
n + = 1
return res
def main ():
Sol = solution ()
Matrix = [
[2, 3]
]
Print Sol.spiralorder (matrix)
if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]54:spiral Matrix