public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if (matrix.length == 0)
            return result;
        init(matrix.length, matrix[0].length);
        while (!closed) {
            result.add(matrix[index[0]][index[1]]);
            next();
        }
        result.add(matrix[index[0]][index[1]]);
        return result;
    }