您的位置:首页 > 编程语言 > Python开发

leetcode.array--54. Spiral Matrix

2017-10-13 16:14 465 查看
题目:54. Spiral Matrix

问题描述:https://leetcode.com/problems/spiral-matrix/description/

意思是说呢,给定一个M*N的二维矩阵,顺时针螺旋打印出其中的所有元素。例如二维数组[[1,2,3],[4,5,6],[7,8,9]],返回[1,2,3,6,9,8,7,4,5]。

我写了一个递归,参数中传入当前前进的方向就好啦。当撞墙了(越界或者已访问)就换方向,而可以换的方向是唯一的。

Python:

class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
rows=len(matrix)
if rows==0:
return []
if rows==1:
return matrix[0]
cols=len(matrix[0])
if cols==0:
return []
def cango(x,y):
return x>=0 and x<rows and y>=0 and y<cols
direct=[(0,1),(1,0),(0,-1),(-1,0)]
vis=set()
def dfs(matrix,step,res,x,y,curDirect):
vis.add((x,y))
res.append(matrix[x][y])
if step==rows*cols-1:
return res
nx,ny=x+curDirect[0],y+curDirect[1]
if cango(nx,ny) and (nx,ny) not in vis:

dfs(matrix,step+1,res,nx,ny,curDirect)
else:
for i in range(4):
nx, ny = x + direct[i][0], y + direct[i][1]
if cango(nx,ny) and (nx,ny) not in vis:
dfs(matrix, step + 1, res, nx, ny, direct[i])
break
res=[]
dfs(matrix, 0, res, 0, 0, (0, 1))
return res

其实也没必要写递归,数据量大就GG了。可能leetcode数据比较水吧。
但是,Discuss里面有个孩子用了一行代码就搞定了,墙都不扶就服你。如下:

class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
return matrix and list(matrix.pop(0)) + self.spiralOrder(list(zip(*matrix))[::-1])

用了递归和zip(),先pop掉第一行,然后加上递归zip剩下的矩阵的逆序,举个例子:
二维矩阵[[1,2,3],[4,5,6],[7,8,9]],先list(matrix.pop(0)),原矩阵只剩下[[4,5,6],[7,8,9]],然后list(zip(*matrix))的结果是[(4,7),(5,8),(6,9)],zip()的一些细节在之前的文章写过了,后面的[::-1]为逆序,也就是此刻spiralOrder的参数变成了[(6,9),(5,8),(4,7)],再然后递归到终点就结束了。至于为什么可以return matrix and ...,是因为and是从左向右计算的,若表达式均为True则返回最后一个表达式的计算结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息