Description
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example
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]
Submissions
这道题主要思路横纵坐标轮换,di和dj正负切换控制遍历方向,i和j表示当前遍历元素的坐标,并将遍历后的元素置为0。首先初始化坐标为(0,0),di为0,dj为1,表示横坐标不变,纵坐标依次加一,横向遍历matrix列表第一行,并添加到结果列表rel中,当第一行遍历结束后,di为1,dj为0,表示横坐标依次加一,纵坐标不变,向下遍历matrix列表最右列,当遍历结束后,di为0,dj为-1,表示横坐标不变,纵坐标依次减一,向左遍历matrix列表最后一行,当遍历结束后,di为-1,dj为0,表示横坐标依次减一,纵坐标不变,向上遍历matrix列表最左列。以此类推,当遍历完每行或每列,即元素已置为0时即改变遍历方向。最后rel列表长度等于matrix元素个数时即遍历完成,返回rel即可。
实现代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: rel, i, j, di, dj = [], 0, 0, 0, 1 if matrix != []: for _ in range(len(matrix) * len(matrix[0])): rel.append(matrix[i][j]) matrix[i][j] = 0 if matrix[(i + di) % len(matrix)][(j + dj) % len(matrix[0])] == 0: di, dj = dj, -di i += di j += dj return rel
参考:https://blog.csdn.net/zysps1/article/details/89364083
最后
以上就是专一野狼最近收集整理的关于LeetCode-54 Spiral Matrix的全部内容,更多相关LeetCode-54内容请搜索靠谱客的其他文章。
发表评论 取消回复