package leetcode;
public class offer_29 {
public int[] spiralOrder(int[][] matrix) {
//空数组
if(matrix==null||matrix.length==0||matrix[0].length==0) {return new int[0];}
int height=matrix.length;
int width=matrix[0].length;
int arr[]=new int[height*width];
int count=0;
int i=0;
int j=0;
//上下左右边界
int up=0;
int down=height-1;
int left=0;
int right=width-1;
while(count<arr.length) {
//上边界
for(j=left;count<arr.length&&j<=right;j++) {
arr[count]=matrix[up][j];
count=count+1;
}
//更新上边界
up=up+1;
//右边界
for(i=up;count<arr.length&&i<=down;i++) {
arr[count]=matrix[i][right];
count++;
}
//更新右边界
right=right-1;
//下边界
for(j=right;count<arr.length&&j>=left;j--) {
arr[count]=matrix[down][j];
count++;
}
//更新下边界
down=down-1;
//左边界
for(i=down;count<arr.length&&i>=up;i--) {
arr[count]=matrix[i][left];
count++;
}
//更新左边界
left=left+1;
}
for (int k : arr) {
System.out.println(k);
}
return arr;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
offer_29 off=new offer_29();
int nums[][]= {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
off.spiralOrder(nums);
}
}