public static int[] spiralOrder(int[][] matrix) {
int m = matrix.length;
if (m == 0) return new int[0];
int n = matrix[0].length;
int[] res = new int[m * n];
int x = 0, y = 0;
int x1 = m - 1, y1= n - 1;
int cnt = 0;
while (x <= x1 && y <= y1) {
if (x == x1) {
for (int j = y; j <= y1; j++) {
res[cnt++] = matrix[x1][j];
}
}
else if (y == y1) {
for (int i = x; i <= x1; i++) {
res[cnt++] = matrix[i][y1];
}
}
else if (x == x1 && y == y1) {
res[cnt++] = matrix[x][y];
}
else {
for (int j = y; j < y1; j++) {
res[cnt ++] = matrix[x][j];
}
for (int i = x; i < x1; i++) {
res[cnt ++] = matrix[i][y1];
}
for (int j = y1; j > y; j--) {
res[cnt ++] = matrix[x1][j];
}
for (int i = x1; i > x; i--) {
res[cnt ++] = matrix[i][y];
}
}
x++;
y++;
x1--;
y1--;
}
//System.out.println(Arrays.toString(res));
return res;
}
顺时针打印矩阵
最新推荐文章于 2023-02-25 17:23:01 发布