First off, great question, and great with images to give examples.
This is a very typical use case for Dijkstra’s Shortest Path algorithm. Read the wiki article - it has code examples too. It finds the shortest path in a graph, which is what you’ve got here, if you imagine that the stars are connected by edges (the yellow paths in the final image).
This kind of algorithm would also typically be used to find the shortest path between cities in travel planning (with the roads as edges in the graph).
Bonus: There are variants of this algorithm that allow you to assign weights to the edges, so some become more favourable than others. These algorithms then select the lowest edge weight sum.