Saturday, November 15, 2014

Converting 2D NxN Array into a List in Spiral Order

Given a 2D NxN array. Print the array into a lost in spiral order.

Example:
If the input array if the following:
00     01     02     03
10     11     12     13
20     21     22     23
30     31     32     33
Then the output will be:
00     01     02     03     13     23     33     32     31     30     20     10     11     12     22     21

The following is a program using Java.

public ArrayList<Character> getSpiralArrayList(char[][] input) {
int size = input.length;
ArrayList<Character> output = new ArrayList<Character>();
if(input[0].length != size) {
System.out.println("Error: Not a NxN Matrix");
return output;
} else {
int top, bottom, left, right;
top = left = 0;
bottom = right = size-1;
for(int layer=0;layer<(size-1); layer++) {
for(int row=left;row<=right;row++)
output.add(input[top][row]);
top++;
for(int column=top; column<=bottom; column++)
output.add(input[column][right]);
right--;
for(int row=right; row>=left; row--)
output.add(input[bottom][row]);
bottom--;
for(int column=bottom; column>=top; column--)
output.add(input[column][left]);
left++;
}
return output;
}
}

Example input = {{'q','w','e'},{'r','t','y'},{'u','i','o'}};
UA-39217154-2