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

Java生成螺旋二维矩阵时奇数长度数组越界异常问题

问题分析与解决

你的问题出在循环条件和奇数矩阵中间元素的处理上:

当n为奇数时,矩阵会剩下中间一个单独的元素,当前代码的循环条件num < n*n +1会导致循环无限执行——因为四个for循环都不会处理这个中间元素,num永远停在n*n,循环条件始终成立,后续边界不断收缩(topRow超过bottomRow、leftCol超过rightCol),虽然不会直接触发数组越界,但会导致程序陷入死循环,可能你误判为数组越界错误。

另外,当前代码的四个for循环逻辑仅处理每一圈的边缘,没有覆盖中间单个元素的场景。

修复后的代码

public class spiral {
    public static void main(String[] args) {
        int n = 5;
        generateSpiralMat(n);
    }

    static void generateSpiralMat(int n) {
        int[][] mat = new int[n][n];
        int topRow = 0, rightCol = n - 1, bottomRow = n - 1, leftCol = 0;
        int num = 1;

        // 修改循环条件:边界未交叉时继续执行
        while (topRow <= bottomRow && leftCol <= rightCol) {
            // 顶部行:从左到右填充
            for (int i = leftCol; i <= rightCol; i++) {
                mat[topRow][i] = num++;
            }
            topRow++;

            // 右侧列:从上到下填充(排除已填充的顶部行)
            for (int j = topRow; j <= bottomRow; j++) {
                mat[j][rightCol] = num++;
            }
            rightCol--;

            // 底部行:从右到左填充(仅当顶部行未超过底部行时执行,避免重复)
            if (topRow <= bottomRow) {
                for (int i = rightCol; i >= leftCol; i--) {
                    mat[bottomRow][i] = num++;
                }
                bottomRow--;
            }

            // 左侧列:从下到上填充(仅当左列未超过右列时执行,避免重复)
            if (leftCol <= rightCol) {
                for (int j = bottomRow; j >= topRow; j--) {
                    mat[j][leftCol] = num++;
                }
                leftCol++;
            }
        }

        printMat(mat);
    }

    static void printMat(int[][] mat) {
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                System.out.print(mat[i][j] + " ");
            }
            System.out.println();
        }
    }
}

关键修复点

  • 循环条件调整:用topRow <= bottomRow && leftCol <= rightCol替代num < n*n +1,确保边界交叉时立即停止循环,避免死循环。
  • 覆盖中间元素:当n为奇数时,最后一轮循环中,顶部行的for循环会直接填充中间的单个元素(此时topRow == bottomRow,leftCol == rightCol)。
  • 添加边界判断:处理底部行和左侧列时,增加额外的边界判断,避免边界交叉后执行不必要的循环,防止潜在的数组越界风险。

内容的提问来源于stack exchange,提问作者Debashis Baral

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:45:10