输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
心得:关键点是矩阵值得索引坐标上着手
模仿打印的顺序,打印的顺序先是左上角-- 右上角 — 右下角–
左下角-- 重回左上角(不断循环) (但是重回左上角的时候,又不能打印之前已经打印过的左上角,所以需要有一个额外的和给定矩阵大小一样的矩阵来来标记已经打印过的位置)
打印顺序 左上角-- 右上角 — 右下角–
左下角-- 分别对应的表示方向的矩阵是
[[]0,1],[1,0],[0,-1],[-1,0]] , 通过控制下一个坐标的位置是否符合条件
if not (0 <= nextRow < rows and 0 <= nextColumn < columns and not visited[nextRow][nextColumn])
来决定是否换方向,也就是是否改变 directionIndex的值,因为下一个矩阵元素是由 directionIndex 决定的 改变了directionIndex的值 也就是在打印的时候转换了方向。
tips: 循环取某一些固定值得方法 : directionIndex = (directionIndex + 1) % 4
下面是详细代码:
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])
visited = [[False] * columns for _ in range(rows)]
total = rows * columns
order = [0] * total
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
row, column = 0, 0
directionIndex = 0
for i in range(total):
order[i] = matrix[row][column]
visited[row][column] = True
nextRow, nextColumn = row + directions[directionIndex][0], column + directions[directionIndex][1]
if not (0 <= nextRow < rows and 0 <= nextColumn < columns and not visited[nextRow][nextColumn]):
directionIndex = (directionIndex + 1) % 4
row += directions[directionIndex][0]
column += directions[directionIndex][1]
return order
只是一些自己的新得,写在博客上只是作为备忘录,方便以后复习的时候回忆思路和方法。
这篇博客介绍如何按顺时针顺序打印矩阵。关键在于跟踪已打印位置,并根据四个方向(左上、右上、右下、左下)更新坐标。详细代码展示了一个解决方案,适用于不同大小的矩阵,可用于复习和备忘。
314





