/** Prints a 2d matrix in spiral order. In the sample 2d matrix below this translates to printing the array items in increasing order. */
public class SpiralPrinter {
private int[][] i2dArray = {
{1, 2, 3, 4, 5},
{14, 15, 16, 17, 6},
{13, 20, 19, 18, 7},
{12, 11, 10, 9, 8},
};
public static void main(String[] args) {
SpiralPrinter printer = new SpiralPrinter();
printer.printSpiral();
}
public void printSpiral()
{
// iterators and high and low bounds for iterations
int row, col, lowrowbound, highrowbound, lowcolbound, highcolbound;
// total number of items in the 2d array
int iTotal = i2dArray.length * i2dArray[0].length;
// counts number of items traversed
int iCounter = 0;
// start with the first element, top-left of the 2d array
row = 0;
col = 0;
// at the beginning the low bounds are 0, 0, and the high bounds are equal to the number of rows and columns in the 2d array.
lowrowbound = 0;
lowcolbound = 0;
highrowbound = i2dArray.length;
highcolbound = i2dArray[0].length;
// stores the items to be printed at the end of the program
StringBuilder sb = new StringBuilder();
// loop until we have run out of items in the matrix
while (iCounter = lowcolbound; col--) {
sb.append(i2dArray[row][col] + ", ");
iCounter++;
}
row--;
col++;
// print left col
for (; row >= lowrowbound; row--) {
sb.append(i2dArray[row][col] + ", ");
iCounter++;
}
// update the bounds so that we don't traverse the same row/col again
col = lowcolbound++ + 1;
row = lowrowbound;
// now repeat with the next row and col
}
System.out.println(sb);
}
}