题目
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 :
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
注意点
1、定义上、下、左、右是为了确定遍历的开始和结束的位置;
2、遍历过程中,需要判断count是否大于0;(是否遍历完成)
3、顺时针遍历,遍历完哪一行,哪一行加一(或减一);
4、遍历过程如下图:
实现
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return result;
int top = 0; //上
int bottom = matrix.length - 1; //下
int left = 0; //左
int right = matrix[0].length - 1; //右
int count = matrix.length * matrix[0].length; //遍历的总数
while (count > 0){
//从左往右遍历上行
for(int i = left; i <= right && count > 0; i ++){
result.add(matrix[top][i]);
count --;
}
//遍历完上行,上行加一
top ++;
//从上往下遍历右行
for (int i = top; i <= bottom && count > 0; i ++){
result.add(matrix[i][right]);
count --;
}
//遍历完右行,右行减一
right --;
//从右往左遍历下行
for (int i = right; i >= left && count > 0; i --){
result.add(matrix[bottom][i]);
count --;
}
//遍历完下行,下行减一
bottom --;
//从下往上遍历左行
for (int i = bottom; i >= top && count > 0; i --){
result.add(matrix[i][left]);
count --;
}
//遍历完左行,左行加一
left ++;
}
return result;
}