It is necessary to track the direction: I solved this question on interviewbit without tracking the direction.
public class Solution {
// DO NOT MODIFY THE ARGUMENTS WITH “final” PREFIX. IT IS READ ONLY
public int[] spiralOrder(final int[][] A) {
int rowu=0;
int coll=A[0].length-1;
int rowd=A.length-1;
int colf=0;
int B[]=new int[A.length*A[0].length];
int k=0;
while(rowu<=rowd && colf<=coll)
{
if(k>B.length-1)
{
break;
}
for(int i=colf;i<=coll;i++)
{
B[k]=A[rowu][i];
k++;
}
rowu++;
if(k>B.length-1)
{
break;
}
for(int i=rowu;i<=rowd;i++)
{
B[k]=A[i][coll];
k++;
}
coll--;
if(k>B.length-1)
{
break;
}
for(int i=coll;i>=colf;i--)
{
B[k]=A[rowd][i];
k++;
}
rowd--;
if(k>B.length-1)
{
break;
}
for(int i=rowd;i>=rowu;i--)
{
B[k]=A[i][colf];
k++;
}
colf++;
}
return B;
}
}