You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

非方阵螺旋矩阵实现遇索引越界问题求助

修复螺旋矩阵生成的索引越界问题

你的代码在处理非方阵时出现索引越界,核心问题是转向判断的步数计算逻辑只适配方阵,非对称的行列数会导致步数计算错误,进而引发数组访问越界。

修复后的实现代码

class Spiral {
    static int[][] spiral(int rows, int columns) {
        int[][] matrix = new int[rows][columns];
        int top = 0;
        int bottom = rows - 1;
        int left = 0;
        int right = columns - 1;
        int currentNum = 1;

        while (currentNum <= rows * columns) {
            // 从左到右填充顶部行
            for (int col = left; col <= right; col++) {
                matrix[top][col] = currentNum++;
            }
            top++; // 顶部行填充完成,收缩上边界

            // 从上到下填充右侧列
            for (int row = top; row <= bottom; row++) {
                matrix[row][right] = currentNum++;
            }
            right--; // 右侧列填充完成,收缩右边界

            // 判断是否还有剩余行需要填充(避免单行时重复填充)
            if (top <= bottom) {
                // 从右到左填充底部行
                for (int col = right; col >= left; col--) {
                    matrix[bottom][col] = currentNum++;
                }
                bottom--; // 底部行填充完成,收缩下边界
            }

            // 判断是否还有剩余列需要填充(避免单列时重复填充)
            if (left <= right) {
                // 从下到上填充左侧列
                for (int row = bottom; row >= top; row--) {
                    matrix[row][left] = currentNum++;
                }
                left++; // 左侧列填充完成,收缩左边界
            }
        }
        return matrix;
    }
}

代码说明

这种实现方式通过边界收缩的逻辑替代原有的步数计算,更直观且适配所有行列组合:

  • 用top、bottom、left、right四个变量标记当前待填充区域的边界
  • 按顺时针顺序依次填充:顶部行→右侧列→底部行→左侧列
  • 每完成一个方向的填充,就收缩对应边界
  • 每次填充前判断边界是否交叉,避免单行/单列时的重复填充或越界访问

测试输入spiral(3,4),会输出符合预期的矩阵:

1  2  3  4
10 11 12 5
9  8  7  6

内容的提问来源于stack exchange,提问作者Kostadin Samardjiev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 22:50:07