Wenn ich Ihren Beitrag gelesen habe, habe ich angefangen zu spielen, also werde ich Ihnen meinen Code poste, vielleicht wird es für Sie halpful sein. Ich habe es für Quadrat getan, wenn Sie für Rechteck brauchen, müssen Sie Schritt X und SchrittY trennen. SIZE wäre in Ihrem Fall ein Eingabeparameter, ich habe es für den Test endgültig statisch.
public class clockwise {
private static final int SIZE = 3;
public static void main(String[] args) {
// int[][] test_matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
int[][] test_matrix = {{1,2,3},{5,6,7},{9,10,11}};
int[][] direction = {{1, 0},{0, 1},{-1, 0},{0, -1}}; //{x,y}
for(int i = 0; i < SIZE; i++) {
for(int j = 0; j < SIZE; j++)
System.out.print(test_matrix[i][j] + " ");
System.out.println("");
}
int x = 0;
int y = 0;
int directionMove = 0;
int stepSize = SIZE;
boolean changeStep = true;
int stepCounter = 0;
for(int i = 0; i < SIZE*SIZE; i++) {
System.out.print(test_matrix[x][y] + " ");
stepCounter++;
if (stepCounter % stepSize == 0) {
directionMove++;
directionMove = directionMove%4;
if(changeStep) { //after first edge one need to decrees step after passing two edges
stepSize--;
changeStep = false;
} else {
changeStep = true;
}
stepCounter = 0;
}
x += direction[directionMove][0];
y += direction[directionMove][1];
}
}
}
Ist die Matrix ein Quadrat? – Keiwan
könnte es sein..aber nicht notwendig –
, aber wenn Sie die Logik für eine quadratische Matrix wissen, dann teilen Sie bitte –