You could probably do it recursively. Define a start point (such as the beginning arrow). Find every combination that Connects to that point(X/4)(skip this if the connector has 4 connections), Define each of the outputs as a new start point. Push onto a stack of start points with start points that don't go closer to the end point on top. repeat. At the end add the combination that lead to the longest path to the end point, then add any other combinations that create the longest paths of dead ends. There is a fun YouTube video that I saw about a program that solves mazes that does it pretty similarly.