Looking at this picture
It appears your problem would be represented well by a directed graph. Give each stop and each junction two nodes in the graph, one for each direction of the train. Dijkstra's algorithm works perfectly on directed graphs, so once you have the problem in that form, the rest is easy.
So for example, in the picture above, starting from A
, we move to junction 1
. From there, there's only one place to move to, junction 2
, so there'd be an arrow from A
--> junction 1
and an arrow from junction 1
--> junction 2
. Regardless of which choice you make, you end up at junction 1
, but moving in the other direction, so we create a separate node from there. From there, you have the option of going to A
or B
.
Notice that I removed one of the J1
's, since it is superfluous (there's only one place to go).
If the train can stop and turn around at stops like A
, we can connect those two nodes by edges in both directions, or just combine them into one node.
You can give the edges weights to specify distances.