54. 螺旋矩阵
题目链接:https://leetcode-cn.com/problems/spiral-matrix/
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:39.3 MB, 在所有 Java 提交中击败了6.47% 的用户
按层遍历
对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于 (top,left)(\textit{top}, \textit{left})(top,left),右下角位于 (bottom,right)(\textit{bottom}, \textit{right})(bottom,right),按照如下顺序遍历当前层的元素。
从左到右遍历上侧元素,依次为 (top,left)(\textit{top}, \textit{left})(top,left) 到 (top,right)(\textit{top}, \textit{right})(top,right)。
从上到下遍历右侧元素,依次为 (top+1,right)(\textit{top} + 1, \textit{right})(top+1,right) 到 (bottom,right)(\textit{bottom}, \textit{right})(bottom,right)。
如果 left<right\textit{left} < \textit{right}left<right 且 top<bottom\textit{top} < \textit{bottom}top<bottom,则从右到左遍历下侧元素,依次为 (bottom,right−1)(\textit{bottom}, \textit{right} - 1)(bottom,right−1) 到 (bottom,left+1)(\textit{bottom}, \textit{left} + 1)(bottom,left+1),以及从下到上遍历左侧元素,依次为 (bottom,left)(\textit{bottom}, \textit{left})(bottom,left) 到 (top+1,left)(\textit{top} + 1, \textit{left})(top+1,left)。
遍历完当前层的元素之后,将 left\textit{left}left 和 top\textit{top}top 分别增加 111,将 right\textit{right}right 和 bottom\textit{bottom}bottom 分别减少 111,进入下一层继续遍历,直到遍历完所有元素为止。
1 |
|
54. 螺旋矩阵
https://pisces34.github.io/2022/02/06/leetcode/54/