Objective:
Implement an iterator for a 2-dimensional array data structure that moves in a clockwise inward spiral
Example:
Input A[4,4] array
01 02 03 04
05 06 07 08
09 10 11 12
13 14 15 16
The above 2-D array would iterate the following way
01 02 03 04 08 12 16 15 14 13 09 05 06 07 11 10
Solution: The problem can be solved in many different ways. I have solved this problem in Java Programming language using recursive way.
public class InwardSprial{
public void top_bottom(T[][] a, int x1, int y1, int x2, int y2) {
for (int i = y1; i < y2; i++) {
display(a[x1][i]);
}
x1 = x1 + 1;
if(!hasNext((x2-x1),(y2-y1))) {
return;
}
for (int j = x1; j < x2; j++) {
display(a[j][y2 - 1]);
}
y2 = y2 - 1;
if(!hasNext((x2-x1),(y2-y1))) {
return;
}
bottom_top(a, x1, y1, x2, y2);
}
private void display(T value) {
System.out.print(value + "\t");
}
private boolean hasNext(int x, int y) {
if (x==0 || y==0) {
return false;
}
return true;
}
private void bottom_top(T[][] a, int x1, int y1, int x2, int y2) {
int i = 0, j = 0;
for (i = y2 - 1; i >= y1; i--) {
display(a[x2 - 1][i]);
}
x2 = x2 -1;
if(!hasNext((x2-x1),(y2-y1))) {
return;
}
for (j = x2 - 1; j >= x1; j--) {
display(a[j][y1]);
}
y1 = y1 +1;
if(!hasNext((x2-x1),(y2-y1))) {
return;
}
top_bottom(a, x1, y1, x2, y2);
}
public static void main(String[] args) throws IOException {
int x=5,y=4;
Integer[][] a = new Integer[x][y];
int num =0;
for (int i=0; iis = new InwardSprial ();
is.top_bottom(a, 0, 0, x, y);
}
}
No comments:
Post a Comment