算法 【模拟】螺旋矩阵 求解代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 public ArrayList<Integer> spiralOrder(int[][] matrix) { ArrayList<Integer> ans = new ArrayList<>(); // 处理空矩阵、空行、空列场景,避免空指针/数组越界 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return ans; } int m = matrix.length; // 矩阵行数 int n = matrix[0].length; // 矩阵列数 // 定义矩阵四个边界指针,初始指向边缘 int left_bound = 0; int right_bound = n - 1; int up_bound = 0; int down_bound = m - 1; // 遍历所有元素后终止循环 while (ans.size() < m * n) { // 方向1:从左到右遍历上边界行,遍历后上边界向下收缩 if (up_bound <= down_bound) { for (int j = left_bound; j <= right_bound; j++) { ans.add(matrix[up_bound][j]); } up_bound++; } // 方向2:从上到下遍历右边界列,遍历后右边界向左收缩 if (left_bound <= right_bound) { for (int i = up_bound; i <= down_bound; i++) { ans.add(matrix[i][right_bound]); } right_bound--; } // 方向3:从右到左遍历下边界行,遍历后下边界向上收缩 if (up_bound <= down_bound) { for (int j = right_bound; j >= left_bound; j--) { ans.add(matrix[down_bound][j]); } down_bound--; } // 方向4:从下到上遍历左边界列,遍历后左边界向右收缩 if (left_bound <= right_bound) { for (int i = down_bound; i >= up_bound; i--) { ans.add(matrix[i][left_bound]); } left_bound++; } } return ans; }