public ArrayList spiralOrder(final List> a) {
ArrayList result = new ArrayList();
int m = a.get(0).size();
int n = a.size();
if(m>1 && n>1){
int loopCounter = (n > m) ? m*2 : n *2 -1 ;
int opr=1;
int i=0,j=0;
int opA=m,opB=n,opC=0,opD=1;
for(int k=0;k < loopCounter ;k++){
if(opr == 1){
int counter =0;
while(counter < opA){
System.out.print(a.get(i).get(j)+ ";");
result.add(a.get(i).get(j));
counter++;
if(j != opA-1){
j++;
}
else{
break;
}
}
opr =2;
continue;
}
if(opr == 2){
i++;
int counter =1;
while(counter < opB){
System.out.print(a.get(i).get(j)+ ";");
result.add(a.get(i).get(j));
counter++;
if( i != opB-1){
i++;
}
else{
break;
}
}
opr =3;
continue;
}
if(opr == 3){
j--;
int counter =j;
while(counter >= opC){
System.out.print(a.get(i).get(j)+ ";");
result.add(a.get(i).get(j));
counter --;
if(j != opC){
j--;
}
else{
break;
}
}
opr =4;
continue;
}
if(opr == 4){
i--;
int counter = i;
while(counter >= opD){
System.out.print(a.get(i).get(j)+ ";");
result.add(a.get(i).get(j));
counter --;
if(i != opD){
i--;
}else{
break;
}
}
opr =1;
j++;
opA = opA -1;
opB = opB -1;
opC= opC +1;
opD = opD+1;
continue;
}
}
}
else if(n ==1){
for(int k=0;k < a.get(0).size();k++){
result.add(a.get(0).get(k));
}
}
// Populate result;
return result;
}