【问题标题】:Spiral Matrix java螺旋矩阵java
【发布时间】:2022-07-21 18:45:03
【问题描述】:

我试图解决这个问题,但没有奏效。 描述: 实现它的静态方法:

  • int[][] spiral(int rows, int columns)
    返回以表格形式出现的二维数组,其中包含从1rows * columns 的数字。表格的大小将由给定的参数指定。
    数字以螺旋方式从顶层角落顺时针填充“表格”。
    例如,对于参数值(3, 4),输出数组应为:
     1  2  3  4
    10 11 12  5
     9  8  7  6
    
    static int[][] spiral(int rows, int columns) {
       int mat[][] = new int[rows][columns];
        int counter = 1;
        int startCol = 0;
        int endCol = columns - 1;
        int startRows = 0;
        int endRows = rows -1;
    
        while (startRows <= endRows && startCol <= endCol){
            for (int i = startCol; i <= endCol; i++){
                mat[startRows][i] = counter;
                counter++;
            }
            startRows++;
    
            for (int j = startRows; j <= endRows; j++){
                mat[j][endCol] = counter;
                counter++;
            }
            endCol--;
    
            for (int l = endCol; l >= startCol; l--){
                mat[endRows][l] = counter;
                counter++;
            }
            endRows--;
    
            for(int y = endRows; y >= startRows; y--){
                mat[y][startCol] = counter;
                counter++;
            }
            startCol++;
        }
    
        return mat;
    }
    

}

预期:

[[1;2;3;4;5;6];
[18;19;20;21;22;7];
[17;28;29;30;23;8];
[16;27;26;25;24;9];
[15;14;13;12;11;10]​​]

实际:

[[1;2;3;4;5;6];
[18;19;20;21;22;7];
[17;28;31;30;23;8];
[16;27;26;25;24;9];
[15;14;13;12;11;10]​​]

【问题讨论】:

  • 您应该使用调试器并单步执行您的代码。看来您的循环执行正确,直到通过中心的最后一行。你可能正确地写了 29 和 30,然后用 31 覆盖 29。

标签: java matrix spiral


【解决方案1】:

while 条件对填充数字有效。 但在每个 for 循环之前,条件必须仍然成立。

while (startRows <= endRows && startCol <= endCol){
    for (int i = startCol; i <= endCol; i++){
        mat[startRows][i] = counter;
        counter++;
    }
    startRows++;

    for (int j = startRows; j <= endRows; j++){
        mat[j][endCol] = counter;
        counter++;
    }
    endCol--;

    if (startRows > endRows) {
        break;
    }
    for (int l = endCol; l >= startCol; l--){
        mat[endRows][l] = counter;
        counter++;
    }
    endRows--;

    if (startCol > endCol) {
        break;
    }
    for(int y = endRows; y >= startRows; y--){
        mat[y][startCol] = counter;
        counter++;
    }
    startCol++;
}

我在返回时添加了两个休息时间。

否则算法相当优雅,也许你可以找到一种方法来清理我的hacky条件。

我没有测试代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多