Internally, the algorithm evaluates many possible paths, and chooses the shortest one.
If you adjust the algorithm slightly, so it calculates an additional penalty for each change in direction, then it will choose the shortest path with the fewest changes in direction.