You should take a look at the Matrix Routing API. This will calculate the "real" distance between each of N x M locations. With this information, you have reduced the issue to the Travelling Salesman Problem. Of course, the TSP is NP-complete, so you can't be certain you've got the optimal answer unless you use a brute force algorithm.
Personally I'd look at a nearest neighbour solution - quick, very simple to code and usually returns a "reasonable", if not optimal solution. You can update to more complex algorithms as necessary:
Pseudo-code below:
- Start at point A
- Matrix routing request to all remaining points.
- Find nearest, this becomes the next Waypoint
- Repeat from step 2.