题目描述:按照螺旋顺序打印矩阵。
题目链接:Leetcode 54. Spiral Matrix
思考思路:就是矩阵的一个搜索遍历,用到思想就是要dx\dy 来控制方向,正如 (0,0,-1,1)这样的方向选择,就是选择不同方向,要思考的就是什么时候转变方向。
代码如下
class Solution(object):
def spiralOrder(self, matrix):
m=len(matrix)
if not m:
return []
n=len(matrix[0])
x,y,dx,dy=0,0,0,1
ans=[]
for k in range(m*n):
ans.append(matrix[x][y])
matrix[x][y]=0 #填充0
if matrix[(x+dx)%m][(y+dy)%n]==0: #越界0
dx, dy = dy , -dx
x += dx
y += dy
return ans
class Solution(object):
def spiralOrder(self, matrix):
if not matrix: return []
rows, cols, result = len(matrix), len(matrix[0]), []
N, x, y, dx, dy = rows * cols, -1, 0, 1, 0
while True:
for i in range(cols):
x, y = x + dx, y + dy
result += matrix[y][x],
rows -= 1
if not rows: return result
dx, dy = -dy, dx
for i in range(rows):
x, y = x + dx, y + dy
result += matrix[y][x],
cols -= 1
if not cols: return result
dx, dy = -dy, dx #这个利用增量来做
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
ans = []
if not matrix or not matrix[0]:
return []
tr = 0
tc = 0
dr = len(matrix) - 1
dc = len(matrix[0]) - 1
while(tr<=dr and tc<=dc):
self.getAns(matrix,tr,tc,dr,dc,ans)
tr += 1
tc += 1
dr -= 1
dc -= 1
return ans
def getAns(self,matrix,tr,tc,dr,dc,ans):
if(tc==dc):
for i in range(tr,dr+1):
ans.append(matrix[i][dc])
elif (tr==dr):
for i in range(tc,dc+1):
ans.append(matrix[tr][i])
else:
curC = tc
curR = tr
while(curC != dc):
ans.append(matrix[tr][curC])
curC += 1
while(curR!=dr):
ans.append(matrix[curR][dc])
curR += 1
while(curC != tc):
ans.append(matrix[dr][curC])
curC -= 1
while(curR != tr):
ans.append(matrix[curR][curC])
curR -= 1