54. Spiral Matrix
来源:互联网 发布:傲剑金蛇数据 编辑:程序博客网 时间:2024/06/06 05:28
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].
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res; int cl = 0, cr = matrix[0].length-1; int rl = 0, rr = matrix.length-1; while (cl <= cr && rl <= rr) { int i = rl, j = cl; while (j <= cr) res.add(matrix[i][j++]); j--; i++; while (i <= rr) res.add(matrix[i++][j]); i--; j--; while (rl != rr && j > cl) res.add(matrix[i][j--]); while (cl != cr && i > rl) res.add(matrix[i--][j]); cl++; cr--; rl++; rr--; } return res; }}
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<Integer>(); if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return res; int rowbegin = 0, rowend = matrix.length-1, 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
- 17 - 01 - 16 计算机网络(06)(虚拟局域网)
- PCI parse MEM/IO range in _CRS in ACPI table
- JAVA_weB中的一些配置
- 数据结构实训之学生信息管理系统
- Java中分割字符串
- 54. Spiral Matrix
- CSS继承性及层叠性
- 1004. Counting Leaves (30)
- Spark1.3从创建到提交:5)Executor启动源码分析
- STL源码剖析——list容器的排序算法sort()
- 爬虫之页面链接获取
- Leetcode Reverse Linked List II 92
- socket基本套接字2(signal和wait)
- mac下在命令行使用sublime text