54. Spiral Matrix
来源:互联网 发布:如何优化网页加载速度 编辑:程序博客网 时间:2024/06/05 18:07
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]
You should return [1,2,3,6,9,8,7,4,5]
.
初始化rowBegin = 0, rowEnd = matrix.length - 1, colBegin = 0, colEnd = matrix[0].length - 1。开始按照螺旋方向添加元素,并加减相应的rowBegin, rowEnd, colBegin, colEnd。注意一行或者一列的情况,要加额外判断,代码如下:
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); if (matrix.length == 0) { return res; } int rowBegin = 0, rowEnd = matrix.length - 1; int colBegin = 0, colEnd = matrix[0].length - 1; while (rowBegin <= rowEnd && colBegin <= colEnd) { for (int i = colBegin; i <= colEnd; i ++) { res.add(matrix[rowBegin][i]); } rowBegin ++; for (int i = rowBegin; i <= rowEnd; i ++) { res.add(matrix[i][colEnd]); } colEnd --; if (rowBegin <= rowEnd) { for (int i = colEnd; i >= colBegin; i --) { res.add(matrix[rowEnd][i]); } } rowEnd --; if (colBegin <= colEnd) { for (int i = rowEnd; i >= rowBegin; i --) { res.add(matrix[i][colBegin]); } } colBegin ++; } return res; }}
0 0
- 54. Spiral Matrix && 59. Spiral Matrix II
- 59. Spiral Matrix II && 54. Spiral Matrix
- LeetCode 54. Spiral Matrix
- [LeetCode]54.Spiral Matrix
- LeetCode --- 54. Spiral Matrix
- [Leetcode] 54. Spiral Matrix
- [leetcode] 54.Spiral Matrix
- 54. Spiral Matrix
- Leetcode-54.Spiral Matrix
- **LeetCode 54. Spiral Matrix
- Leetcode 54. Spiral Matrix
- [leetcode] 54. Spiral Matrix
- 54. Spiral Matrix
- leetcode 54. Spiral Matrix
- 54. Spiral Matrix LeetCode
- 54. Spiral Matrix
- 54. Spiral Matrix
- leetcode 54. Spiral Matrix
- ContentProvider(内容提供者)和ContentResolve(内容访问者)
- pay attention to \r \n
- test
- 【寒江雪】2017.2.15切题
- Leetcode 92. Reverse Linked List II
- 54. Spiral Matrix
- 内容提供访问者
- spring安全框架系列springSecurity
- CSS属性之文本(Text)属性 常用14个
- 56 Merge Intervals
- Linux内存管理机制
- 139 Word Break
- 从零开始学习C++ (对象)
- 1103. Integer Factorization (30)