import java.util.*;
// 1 2 3
// 4 5 6
// 7 8 9
// 螺旋 1 2 3 6 9 8 7 4 5
public class Solution {
public int[] printMatrix (int[][] matrix) {
// 判断空
if (matrix.length == 0 || matrix[0].length == 0) return null;
// left 从1--2--3
// right 从3--2--1
// top 从1--4--7
// bottom 从7--4--1
int left = 0, right = matrix[0].length - 1;
int top = 0, bottom = matrix.length - 1;
// res[]的指针索引index
int index = 0;
// res[]的长度count==计算m*n
int count = matrix.length * matrix[0].length;
// 创建数组存放
int[] res = new int[count];
// 遍历
while (top < (matrix.length+1)/2 && left < (matrix[0].length+1)/2) {
// 1.上面1--2--3左往右
for (int i = left; i <= right; i++) {
res[index++] = matrix[top][i]; // 添加matrix[0][0],matrix[0][1],matrix[0][2]
}
// 2.右边3--6--9上往下,3(即matrix[0][2])已经添加,则top+1
for (int i = top+1; i <= bottom; i++) {
res[index++] = matrix[i][right]; // 添加matrix[1][2],matrix[2][2]
}
// 3.底面9--8--7右往左,9(即matrix[2][2])已经添加,则right-1
// 上述条件top < (matrix.length+1)/2,以防矩阵过于大的时候重复
for (int i = right-1; top != bottom && i >= left; i--) {
res[index++] = matrix[bottom][i]; // 添加matrix[2][1],matrix[2][0]
}
// 4.左边7--4--1下往上,7(即matrix[2][0])已经添加,则bottom-1
// 添加matrix[0][0]重复,冲突 top+1
// 上述条件left < (matrix[0].length+1)/2,以防矩阵过于大的时候重复
for (int i = bottom-1; left != right && i >= top+1; i--) {
res[index++] = matrix[i][left]; // 添加matrix[1][0]
}
// 一圈后,top+1; bottom -1; left+1; right-1
// 缩小范围
top++;
bottom--;
left++;
right--;
}
return res;
}
}