File size: 1,248 Bytes
c574d3a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/**
* Spiral Matrix
*/
public class SpiralMatrix {
public static int[][] spiralMatrix(int count) {
int[][] result = new int[count][count];
int rowStart = 0;
int rowEnd = count - 1;
int columnStart = 0;
int columnEnd = count - 1;
int counter = 1;
while (columnStart <= columnEnd && rowStart <= rowEnd) {
// Top section
for (int i = columnStart; i <= columnEnd; i++) {
result[rowStart][i] = counter;
counter++;
}
rowStart++;
// Right Section
for (int i = rowStart; i <= rowEnd; i++) {
result[i][columnEnd] = counter;
counter++;
}
columnEnd--;
// bottom section
for (int i = columnEnd; i >= columnStart; i--) {
result[rowEnd][i] = counter;
counter++;
}
rowEnd--;
// left section
for (int i = rowEnd; i >= rowStart; i--) {
result[i][columnStart] = counter;
counter++;
}
columnStart++;
}
return result;
}
public static void main(String[] args) {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
System.out.print(SpiralMatrix.spiralMatrix(6)[i][j] + " ");
}
System.out.println("");
}
}
} |