Please be careful of m*n and n*n matrix.
Boundary conditions are important.
static void spiralTraversal(int[][] a){
int r = a.length;
int c = a[0].length;
//System.out.println(c);
int r1 = 0, r2 = r-1, c1 = 0, c2 = c-1;
while(r1 <= r2 && c1 <= c2)
{
//System.out.println(r1+","+c2);
for (int i = r1; i <= c2; i ++)
{
System.out.print(a[r1][i]+ " ");
}
r1++;
for(int i = r1; i<= r2 && r1 <= r2; i++)
{
System.out.print(a[i][c2]+ " ");
}
c2--;
for(int i = c2; i>=c1 && c1 <= c2; i--)
{
System.out.print(a[r2][i]+ " ");
}
r2 --;
for(int i = r2; i>=r1; i--)
{
System.out.print(a[i][c1]+ " ");
}
c1++;
}