Here is some of the variations:
public class SpiralMatrix {
private static int[][] createSpiralMatrix(int size) {
int[][] matrix = new int[size][size];
int row = 0, col = -1;
int value = 1;
boolean horizontal = true;
boolean increasing = true;
boolean finish = false;
while(!finish) {
finish = true;
if (horizontal && increasing) {
while(tryAndSet(matrix, row, col + 1, value)) {
finish = false;
col++;
value++;
}
} else if (horizontal && !increasing) {
while(tryAndSet(matrix, row, col - 1, value)) {
finish = false;
col--;
value++;
}
} else if (!horizontal && increasing) {
while(tryAndSet(matrix, row + 1, col, value)) {
finish = false;
row++;
value++;
}
} else {
while(tryAndSet(matrix, row - 1, col, value)) {
finish = false;
row--;
value++;
}
}
if (!horizontal) {
increasing = !increasing;
}
horizontal = !horizontal;
}
return matrix;
}
private static boolean tryAndSet(int[][] matrix, int row, int col, int value) {
if (row < 0 || col < 0 || row >= matrix.length || col >= matrix[row].length || matrix[row][col] != 0) {
return false;
}
matrix[row][col] = value;
return true;
}
private static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for(int j = 0; j < matrix[i].length; j++) {
System.out.print("\t" + matrix[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
try {
int[][] spiralMatrix = createSpiralMatrix(40);
printMatrix(spiralMatrix);
} catch (Throwable th) {
th.printStackTrace();
}
}