# Easy 2ms Java Recursive Solution, for both Spiral Matrix I and II

• Sprial Matrix 1

``````public List<Integer> spiralOrder(int[][] matrix) {
if(matrix.length==0) return new ArrayList<Integer>();
return spiralOrderRecursive(matrix, 0);
}
public List<Integer> spiralOrderRecursive(int[][] matrix, int level) {
List<Integer> result = new ArrayList<Integer>();
if(matrix.length-2*level==1) return result;
for(int righ = level+1;righ<matrix.length-level; righ++) result.add(matrix[righ][matrix[0].length-level-1]);
if(matrix[0].length-2*level==1) return result;
for(int tail = matrix[0].length-level-2;tail>=level; tail--) result.add(matrix[matrix.length-level-1][tail]);
if(matrix.length-2*level==2) return result;
for(int left = matrix.length-level-2;left>level; left--) result.add(matrix[left][level]);
if(matrix[0].length-2*level==2) return result;
return result;
}
``````

Sprial Matrix 2

``````public int[][] generateMatrix(int n) {
if(n==0) return new int[n][n];
return generateMatrixRecursive(new int[n][n], 0, 1);
}
public int[][] generateMatrixRecursive(int[][] matrix, int level, int num) {