问题描述:
Given a matrixof 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 shouldreturn [1,2,3,6,9,8,7,4,5].
问题分析:
显然遍历的方向为先向右遍历,再向下遍历,再向左遍历,最后往上遍历;然后循环往复;其中最终的是判断终止的位置;
使用left,right,top,bottom来分别记录当前未遍历数据块的最左端,最右端,最上端,最下端左边;倘若发生left>right或者top>bottom情况,则表示遍历结束;
而以向右遍历为例,向右遍历了整行之后,该行已经遍历完,则未遍历的数据块top端需要下一一位,即top++;此时有可能发生的情况时top++后,超过了bottom,则此时遍历结束;
代码:
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if ((matrix == null) || (matrix.length == 0) || (matrix[0].length == 0))
return result;
int left = 0; int right = matrix[0].length - 1;
int top = 0; int bottom = matrix.length - 1;
while (true) {
// ==== 先向右遍历 ===== //
for (int j = left; j <= right; j++)
result.add(matrix[top][j]);
top++; // 遍历后要注意更新四个维度的值
// 判断是否还需要继续遍历
if (top > bottom) break;
// ===== 向下遍历 ===== //
for (int i = top; i <= bottom; i++)
result.add(matrix[i][right]);
right--;
if (left > right) break;
// ===== 向左遍历 ===== //
for (int j = right; j >= left; j--)
result.add(matrix[bottom][j]);
bottom--;
if (top > bottom) break;
// ===== 向上遍历 ===== //
for (int i = bottom; i >= top; i--)
result.add(matrix[i][left]);
left++;
if (left > right) break;
}
return result;
}
}