Spiral Matrix java

807 Views Asked by At

I tried to solve the problem, but it didn't work. description: implement its static method:

  • int[][] spiral(int rows, int columns)
    Return a two-dimensional array coming in the form of a table and containing numbers from 1 up to rows * columns. The size of the table will be specified by the given parameters.
    Numbers fill the "table" clockwise from the top-level corner in a spiral manner.
    For example, for parameter values (3, 4), the output array should be:
     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;
    }
    

}

Expected :

[[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]]

Actual :

[[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]]

1

There are 1 best solutions below

2
Joop Eggen On

The while condition is valid for filling a number. But before every for loop the condition must still hold.

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++;
}

I added two breaks on going back.

Otherwise the algorithm is quite elegant, and maybe you can find a way to clean up my hacky conditions.

I did not test the code.

You might have written tracing code to see the logic. A log statement after every counter++;.