Max.ZiLvova
Max.ZiLvova

Reputation: 1

Spiral Matrix java

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

}

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

Upvotes: 0

Views: 1193

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109557

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

Upvotes: 0

Related Questions