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 static List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> result=new ArrayList<Integer>();
if(matrix==null||matrix.length<=0)
return result;
int len1=matrix.length,len2=matrix[0].length,x=0,y=0;
while(len1>0&&len2>0){
if(len1==1){
for(int i=0;i<len2;i++)
result.add(matrix[x][y++]);
break;
}else if(len2==1){
for(int i=0;i<len1;i++)
result.add(matrix[x++][y]);
break;
}
for(int i=0;i<len2-1;i++)
result.add(matrix[x][y++]);
for(int i=0;i<len1-1;i++)
result.add(matrix[x++][y]);
for(int i=0;i<len2-1;i++)
result.add(matrix[x][y--]);
for(int i=0;i<len1-1;i++)
result.add(matrix[x--][y]);
x++;
y++;
len1-=2;
len2-=2;
}
return result;
}

本文介绍了一种从矩阵中按螺旋顺序获取元素的方法,并通过示例代码详细解释了实现过程。
398

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



