I can think of a general solution involving the use of ST_Startpoint and ST_Endpoint, although it only really works if your paths aren't circular. The idea is checking to see if the startpoint of line 1 is closer to the startpoint of line 2 than it is to the endpoint of line 2. Code, self-joining a table with all the paths:
case when ...
Even though you have instructed to use an undirected graph, you must still use set a cost and a reverse_cost (which can be the same).
SELECT gid as id, source, target,
length:: double precision AS cost,
length:: double precision AS reverse_cost
See the examples from the doc:
SELECT * FROM pgr_dijkstra(
'SELECT id, ...