Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5].
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> rec = new ArrayList<Integer>();
if(matrix.length == 0||matrix[0].length == 0||matrix == null)
return rec;
int m = matrix.length,n = matrix[0].length;
int x1 = 0,y1 = 0,x2=m-1,y2=n-1;
while(m>1&&n>1)
{
x2 = x1+m-1;
y2 = y1+n-1;
for(int j=y1;j<y2;j++)
{
rec.add(matrix[x1][j]);
System.out.println(matrix[x1][j]);
}
for(int i=x1;i<x2;i++)
{
rec.add(matrix[i][y2]);
System.out.println(matrix[i][y2]);
}
for(int j=y2;j>y1;j--)
{
rec.add(matrix[x2][j]);
System.out.println(matrix[x2][j]);
}
for(int i=x2;i>x1;i--)
{
rec.add(matrix[i][y1]);
System.out.println(matrix[i][y1]);
}
x1++;
y1++;
m -= 2;
n -= 2;
}
x2 = x1+m-1;
y2 = y1+n-1;
if(m==1&&n!=0)
{
for(int i=y1;i<=y2;i++)
rec.add(matrix[x2][i]);
return rec;
}
if(n==1&&m!=0)
{
for(int i=x1;i<=x2;i++)
rec.add(matrix[i][y2]);
return rec;
}
return rec;
}
}