采用递归的思想,每次都按顺时针的方向取数组的最外边,直到取出所有数组的元素为止

import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
    ArrayList<Integer> res = new ArrayList<Integer>();
    if (matrix == null || matrix.length == 0) {
        return res;
    }
    if (matrix[0].length == 0) {
        return res;
    }
    int n = matrix.length * matrix[0].length;
    int rend = matrix[0].length - 1;
    int cend = matrix.length - 1;

               spiral(res, matrix, 0, rend, 0, cend, n);

    return res;

}

public void spiral(ArrayList<Integer> res, int[][] matrix, int rs, int re,
                   int cs, int ce, int n) {
    for (int i = rs; i <= re; i++) {
        res.add(matrix[cs][i]);
    }
    if (res.size() == n) {
        return;
    }
    if (ce - cs > 1) {
        for (int i = cs + 1; i < ce; i++) {
            res.add(matrix[i][re]);
        }
    }
    for (int i = re; i >= rs; i--) {
        res.add(matrix[ce][i]);
    }
    if (res.size() == n) {
        return;
    }
    for (int i = ce - 1; i > cs; i--) {
        res.add(matrix[i][rs]);
    }
    if (res.size() == n) {
        return;
    }
    spiral(res, matrix, rs + 1, re - 1, cs + 1, ce - 1, n);
}

}