螺旋矩阵 java

Spiral Matrix java

提问人:Max.ZiLvova 提问时间:7/21/2022 最后编辑:mattMax.ZiLvova 更新时间:7/21/2022 访问量:632

问:

我试图解决这个问题,但没有用。 描述: 实现其静态方法:

  • 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;10年23;8];
[16;27;16 倍25;24;9];
[15;14;13;12;11;10]]

实际:

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

Java 矩阵 螺旋

评论

0赞 matt 7/21/2022
应使用调试器并逐步执行代码。您的循环似乎在穿过中心的最后一行之前执行正确。你可能写对了 29 和 30,然后用 31 覆盖 29。

答:

0赞 Joop Eggen 7/21/2022 #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++;
}

我在回去时增加了两个休息时间。

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

我没有测试代码。

您可能已经编写了跟踪代码来查看逻辑。每个 .counter++;

评论

0赞 matt 7/21/2022
似乎他们已经设置了他们的for循环,他们可以消除额外的检查。我想这与行条件的变化有关,但列迭代从不检查它是否仍在有效行中。为什么不使用基于计数器的休息条件呢?
0赞 Joop Eggen 7/21/2022
@matt检查计数器更容易,但更神奇,因为可以保证索引保持在不断滑动的矩形中。请注意,如果我的答案不正确,我不会感到惊讶。