题目描述(传送门)
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
代码解析
import java.util.Arrays;
/**
* @ClassName interview29
* @Description :TODO
* @Author Josvin
* @Date 2021/06/04/12:58
*/
public class interview29 {
public static void main(String[] args) {
int[][] mm = {{2},{2},{2}};//{{}, {3,2,1}, {4, 5, 6}{4, 5, 6}, {7, 8, 9}, {10, 11, 12}};
System.out.println(Arrays.toString(spiralOrder(mm)));
}
public static int[] spiralOrder(int[][] matrix) {
// 处理数组为空的情况
if (matrix.length == 0) {
return new int[]{};
}
int row = matrix.length;
int col = matrix[0].length;
// 结果数组
int[] ans = new int[row * col];
int[] xstep = {0, 1, 0, -1};
int[] ystep = {1, 0, -1, 0};
// 记录顺时针旋转过程中,四个方向不断迭代过程中的步数,4,3,2,2,1,1 就是右4下3左2上2右1下1
int[] flag = new int[row * col];
// 初始化
for (int i = 0; i < flag.length;) {
flag[i++] = col ;
if (i < flag.length) {
flag[i++] = row-1;
}
row--;
col--;
if (row <= 0 && col <= 0) {
break;
}
}
int xx = 0;
int yy = 0;
int j = 0;int tt = 1;
for (int i = 0; i < ans.length; ) {
int tmp = flag[j++];
while (tmp > 0) {
switch (tt) {
case 1:
ans[i++] = matrix[xx][yy];
xx += xstep[0];
yy += ystep[0];
if(tmp==1) {
yy--;
xx++;
tt=2;
}
tmp--;
continue;
case 2:
ans[i++] = matrix[xx][yy];
xx += xstep[1];
yy += ystep[1];
if(tmp==1) {
xx--;
yy--;
tt=3;
} tmp--;
continue;
case 3:
ans[i++] = matrix[xx][yy];
xx += xstep[2];
yy += ystep[2];
if(tmp==1) {
xx--;
yy++;
tt=4;
}tmp--;
continue;
case 4:
ans[i++] = matrix[xx][yy];
xx += xstep[3];
yy += ystep[3];
if(tmp==1) {
xx++;
yy++;
tt=1;
}tmp--;
continue;
}
}
}
return ans;
}
}