# Simple DP recursive solution

• This can be considered as a DP problem.

Every step, we add the out layer of the matrix into the result array clockwise, then call the function recursively to adding the inside sub matrix.

``````public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> result = new ArrayList<Integer> ();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return result;
helper(matrix, result, 0, 0, matrix.length - 1, matrix[0].length - 1);
return result;
}

private void helper(int[][] matrix, ArrayList<Integer> result, int i_start, int j_start, int i_end, int j_end) {
// stop situation
if (i_start > i_end || j_start > j_end)
return;
// only one element in the sub matrix
if (i_start == i_end && j_start == j_end) {
return;
}
// only one row in the sub matrix
if (i_start == i_end) {
for (int j = j_start; j <= j_end; j++)
return;
}
// only one column in the sub matrix
if (j_start == j_end) {
for (int i = i_start; i <= i_end; i++)
return;
}
// other cases, recursive adding all
for (int j = j_start; j < j_end; j++)
for (int i = i_start; i < i_end; i++)