package
com.ytx.array;
import
java.util.ArrayList;
import
java.util.List;
/** 题目: spiral-matrix
* 描述: 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].
*
@author
yuantian xin
* 给你一个m*n的矩阵,以螺旋顺序输出其中的元素。
*
* 使用四个数字分别记录上下左右四个边界的位置,不断循环收窄这些边界,最终当两个边界重叠时,结束循环。
*/
public
class
Spiral_matrix {
public
ArrayList<Integer> spiralOrder(int[][]
matrix) {
ArrayList<Integer>
arrayList
= new
ArrayList<Integer>();
if(matrix
==
null ||
matrix.length
== 0) {
return
arrayList;
}
//左右上下四个边界
int
left = 0;
int
right =
matrix[0].length
- 1;
int
top = 0;
int
bottom =
matrix.length
- 1;
//循环收窄边界,螺旋遍历,边界都是向中间收窄
for( ; ;) {
//上边,从左到右
for(int
i
= left;
i
<= right;
i++) {
arrayList.add(matrix[top][i]);
}
//横向遍历完上边一行之后,上边界增加向中间收窄,所以++top,再判断上下边界是否重叠
if(++top
>
bottom)
break;
//右边,从上到下
for(int
i
= top;
i
<= bottom;
i++) {
arrayList.add(matrix[i][right]);
}
//竖向遍历完右边一列之后,右边界减少向中间收窄,所以--right,再判断左右边界是否重叠
if(left
> --right)
break;
//下边,从右向左
for(int
i
= right;
i
>= left;
i--) {
arrayList.add(matrix[bottom][i]);
}
//横向遍历下边一行,下边界减少向中间收窄,所以--bottom,再判断上下边界是否重叠
if(top
> --bottom)
break;
//左边,从下到上
for(int
i
= bottom;
i
>= top;
i--) {
arrayList.add(matrix[i][left]);
}
//竖向遍历左边一列,左边界增加向中间收窄,所以++left,再判断左右边界是否重叠
if(++left
>
right)
break;
}
return
arrayList;
}
public
static
void main(String[]
args) {
/*int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};*/
int
[][]
matrix = {{1},{2}};
ArrayList<Integer>
list
= new
ArrayList<Integer>();
list
=
new Spiral_matrix().spiralOrder(matrix);
for(Integer
i
: list) {
System.out.print(i
+
" ");
}
}
}
本文介绍了一种算法,用于按螺旋顺序遍历二维矩阵中的所有元素。通过定义四个边界并逐步向内收缩,实现矩阵元素的有效遍历。
874

被折叠的 条评论
为什么被折叠?



