螺旋矩阵用java实现
时间: 2023-02-07 20:57:07 浏览: 62
螺旋矩阵是指将一个矩阵中的数字按照螺旋的顺序依次排列在一个一维数组中。
下面是用 Java 实现螺旋矩阵的一种方法:
```
public class SpiralMatrix {
public static int[] spiralOrder(int[][] matrix) {
if (matrix == null || matrix.length == 0) {
return new int[0];
}
int rows = matrix.length, columns = matrix[0].length;
int[] result = new int[rows * columns];
int index = 0;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
result[index++] = matrix[top][column];
}
for (int row = top + 1; row <= bottom; row++) {
result[index++] = matrix[row][right];
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
result[index++] = matrix[bottom][column];
}
for (int row = bottom; row > top; row--) {
result[index++] = matrix[row][left];
}
}
left++;
right--;
top++;
bottom--;
}
return result;
}
}
```
在上面的代码中, 我们定义了 4 个变量 `left`, `right`, `top`, `bottom` 分别表示矩阵的左边界、右边界、上边界和下边界。每次将这 4 个边界向内缩小 1, 直到左边界大于右边界或上边界大于下边界为止。在每次循环中, 我们依次从左到右遍历上边界的所有元素, 从上到下遍历右边界的所有元素, 从右到左遍历下边界的所有元素, 从下到上遍历左边界的所有元素。
示例:
```
int[][] matrix = {{1, 2,