螺旋矩阵 通过directions来改变方向,[0,1],[1,0],[0,-1],[-1,0]分别表示右、下、左、上。第一个维度表示行的偏移量,第二个维度表示列的偏移量。遇到非法位置(访问过或者超出边界]就转向.
python3题解:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return list()
rows,columns = len(matrix),len(matrix[0]) #行数 列数
total = rows * columns
row,column = 0,0 #初始位置
directions = [[0,1],[1,0],[0,-1],[-1,0]]
direction_index = 0
visit = [[False] * columns for _ in range(rows)]
order = [0]*total
for i in range(total):
order[i] = matrix[row][column]
visit[row][column] = True
nextrow,nextcolumn = row + directions[direction_index][0],column + directions[direction_index][1]
if not(0 <= nextrow <rows and 0 <= nextcolumn <columns and not visit[nextrow][nextcolumn]):#这个矩阵位置如果非法,就改变方向
direction_index= (direction_index+1)%4
row += directions[direction_index][0]
column += directions[direction_index][1]
return order