Leecode 54. Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
感觉有点像在写个游戏,和以前写的扫雷判断条件有点像,比较简单。
代码如下:
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
x = len(matrix)
if(x == 0):
return matrix
if(x == 1):
return matrix[0]
y = len(matrix[0])
turnR = True
turnL = False
Down = False
Up = False
sumNum = x*y
curx, cury = 0, 0
WallR = y-1
WallL = 0
WallBottom = x-1
WallTop = 1
output = [matrix[curx][cury]]
sumNum -= 1
#print(finalX,finalY)
while(sumNum>0):
if(cury==WallR and turnR):
turnR = False
Down = True
WallR -= 1
if(cury==WallL and turnL):
turnL = False
Up = True
WallL += 1
if(curx==WallTop and Up):
Up = False
turnR =True
WallTop += 1
if(curx==WallBottom and Down):
Down = False
turnL = True
WallBottom -= 1
if(turnR):
cury += 1
if(turnL):
cury -= 1
if(Down):
curx += 1
if(Up):
curx -= 1
sumNum -= 1
output += [matrix[curx][cury]]
return output
时间 40%+ 复杂度为O(n),感觉时间不是很快啊
看了discuss 里面的代码,发现一整块数组一起搬回更快,一个一个还是慢了,这边用x in Karray 用得很棒,学习一下编一下。
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if matrix == []:
return []
if len(matrix) == 1:
return matrix[0]
if len(matrix[0]) == 1:
return [x[0] for x in matrix]
top = 0
bottom = len(matrix)
left = 0
right = len(matrix[0])
res = []
while top<bottom and right>left:
res += matrix[top][left:right]
top += 1
res += [x[right-1] for x in matrix[top:bottom]]
right -= 1
if top < bottom:
res += matrix[bottom-1][right-1:left:-1]
bottom -= 1
if left < right:
res += [x[left] for x in matrix[bottom:top-1:-1]]
left += 1
return res