54. Spiral Matrix
来源:互联网 发布:京东运营和淘宝运营 编辑:程序博客网 时间:2024/06/01 08:16
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 List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
// 特殊情况处理
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return result;
}
int rowBegin = 0, rowEnd = matrix.length - 1, colBegin = 0, colEnd = matrix[0].length - 1;
while(rowBegin <= rowEnd && colBegin <= colEnd){
// 首先从左向右遍历
for(int j = colBegin; j <= colEnd; j++){
result.add(matrix[rowBegin][j]);
}
rowBegin++;
// 然后从上到下遍历
for(int i = rowBegin; i <= rowEnd; i++){
result.add(matrix[i][colEnd]);
}
colEnd--;
// 然后从右向左遍历,从右向左遍历的时候要判断是否还有元素
if(rowBegin <= rowEnd){
for(int j = colEnd; j >= colBegin; j--){
result.add(matrix[rowEnd][j]);
}
rowEnd--;
}
// 然后从下向上遍历,从下向上遍历的时候要判断是否还有元素
if(colBegin <= colEnd){
for(int i = rowEnd; i >= rowBegin; i--){
result.add(matrix[i][colBegin]);
}
colBegin++;
}
}
return result;
}
- 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
- HttpClient忽略证书访问HTTPS接口
- JavaWeb中的路径考察
- FileMapping漫谈
- Android-多列表的项目(Rxjava+Rtrofit+Recyclerview+Glide+Adapter封装)之(一)项目架构
- java写二元一次方程组求解
- 54. Spiral Matrix
- 错误记录
- Windows下用VS2015编译FreeSWITCH
- RunLoop详解
- disabled使用
- 349. Intersection of Two Arrays
- android中的定时器
- Timer定时器
- 读取 android /system/build.prop 的最简单方法