螺旋矩阵
https://leetcode.cn/problems/spiral-matrix/description/
题目分析
跟螺旋矩阵类似,顺时针先打印最外圈元素,然后顶点索引递进,打印内圈元素,在打印一圈元素时,分别沿着4个方向打印,然后继续打印内圈元素;
编程实现
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList();
if(matrix == null || matrix.length <= 0){
return list;
}
int left = 0;
int right = matrix[0].length-1;
int bottom = matrix.length - 1;
int top = 0;
while(left <= right && top <= bottom){
//打印行
for(int i = left;i <= right;i++){
list.add(matrix[top][i]);
}
//打印右侧
for(int i = top+1;i <= bottom;i++){
list.add(matrix[i][right]);
}
//打印最底行,top!= bottom ,只有一行情况下 6 7 9
if(top != bottom){
for(int i = right -1;i >= left;i--){
list.add(matrix[bottom][i]);
}
}
/**
打印最左侧 left!=right 条件,只有一列情况下
6
7
9
*/
if(left != right){
for(int i = bottom -1;i > top;i--){
list.add(matrix[i][left]);
}
}
left++;
right--;
bottom--;
top++;
}
return list;
}