Spiral Matrix
Given a matrix of_m_x_n_elements (_m_rows,_n_columns), return all elements of the matrix in spiral order.
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]Analysis
Simulation 模拟法
也就是按照人实现的方式,顺时针遍历矩阵即可。
标记已遍历的元素避免重复遍历陷入死循环,两种方法:
1 新建一个二维数组seen[m][n],seen[i][j]对应matrix[i][j],遍历过的元素设为true
2 设定上下左右四个边界值,即rowLower, rowUpper, colLower, colUpper, 在转换遍历方向时增减边界值的大小
Layer-by-Layer
其实是转化思路,从另一个角度看,spiral遍历时恰好是一层一层元素的顺时针输出:
@LeetCode
Solution
Simulation - Setting Upper Lower Bounds ofRow, Column indexes - (3ms 10.49%)
Simulation - Additional auxiliary matrix seen[][] for visited elements
Layer by Layer
Reference
Last updated
Was this helpful?