NC38 螺旋矩阵
描述
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
示例1
输入:
[[1,2,3],[4,5,6],[7,8,9]]
复制
返回值:
[1,2,3,6,9,8,7,4,5]
import java.util.* ;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> ans = new ArrayList<>() ;
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return ans ;
}
int left = 0 , right = matrix[0].length-1 ;
int top = 0 , bottom = matrix.length-1 ;
while(left < (matrix[0].length + 1) / 2 && top < (matrix.length + 1) / 2){
for(int i = left ; i <= right ; i++ ){
ans.add(matrix[top][i]) ;
}
for(int i = top+1 ; i <= bottom ; i++){
ans.add(matrix[i][right]) ;
}
for(int i = right -1 ; top != bottom && i >= left ; i--){
ans.add(matrix[bottom][i]) ;
}
for(int i = bottom -1 ; left != right && i > top ; i--){
ans.add(matrix[i][left]) ;
}
top++ ;
left++ ;
right-- ;
bottom-- ;
}
return ans ;
}
}