public final class SpiralMatrix { /** * @Description * @Author fucheng * @Date 2021-9-9 15:45 * @Param [] * @return int[][] */ private int[][] construct(int h, int w) { int[][] arr = new int[h][w]; int height = arr.length; int weight = 0; int temp = 1; System.err.println("arr.length=" + height); for (int i = 0; i < height; ++i) { if (weight == 0) weight = arr[i].length; for (int j = 0; j < weight; ++j) { arr[i][j] = temp; ++temp; } } return arr; } /** * @Description * @Author fucheng * @Date 2021-9-9 15:45 * @Param [matrix] * @return java.util.List<java.lang.Integer> */ public ArrayList<Integer> spiralOrder1(int[][] matrix) { int height = matrix.length; if (height == 0) return new ArrayList<>(0); int weight = matrix[0].length; int size = weight * height; ArrayList<Integer> list = new ArrayList<>(size); int max_h_index = height - 1; int max_w_index = weight - 1; int index1 = 0, index2 = 0, index3 = 0, index4 = 0; while (list.size() < size) { // 从左往右 for (int j = index1; j <= max_w_index - index2; ++j) { list.add(matrix[index1][j]); } ++index1; if (list.size() == size) return list; //右侧 从上到下 for (int j = index1; j <= max_h_index - index2; ++j) { list.add(matrix[j][max_w_index - index2]); } ++index2; if (list.size() == size) return list; //下侧从右到左 for (int j = max_w_index - index2; j >= index3; --j) { list.add(matrix[max_h_index - index3][j]); } ++index3; if (list.size() == size) return list; //右侧从下到上 for (int j = max_h_index - index3; j > index4; --j) { list.add(matrix[j][index4]); } ++index4; if (list.size() == size) return list; } return list; } /** * @Description * @Author fucheng * @Date 2021-9-10 15:35 * @Param [matrix] * @return java.util.ArrayList<java.lang.Integer> */ public ArrayList<Integer> spiralOrder(int[][] matrix) { int height = matrix.length; if (height == 0) return new ArrayList<>(0); int weight = matrix[0].length; int size = weight * height; ArrayList<Integer> list = new ArrayList<>(size); int top = 0, bottom = height - 1, left = 0, right = weight - 1; while (top <= bottom && left <= right) { // 顶部:左 -> 右, 列变,行不变 for (int i = left; i <= right; i++) { list.add(matrix[top][i]); } ++top; // 右侧:上 -> 下, 行变,列不变 for (int i = top; i <= bottom; i++) { list.add(matrix[i][right]); } --right; // 底部:右 -> 左, 列变,行不变 for (int i = right; i >= left && top <= bottom; i--) { list.add(matrix[bottom][i]); } --bottom; // 左侧: 下 -> 上, 行变,列不变 for (int i = bottom; i >= top && left <= right; i--) { list.add(matrix[i][left]); } ++left; } return list; } public static void main(String[] args) { SpiralMatrix matrix = new SpiralMatrix(); // System.err.println(matrix.spiralOrder(matrix.construct(3, 4))); // System.err.println(matrix.spiralOrder(matrix.construct(4, 3))); //System.err.println(matrix.spiralOrder(matrix.construct(5, 6))); System.err.println(matrix.spiralOrder(matrix.construct(3, 1))); } }