All Paths
Given a txt file that consists of graph data, output all the possible paths that begin and end with the first two characters in the first line of the file.
Consider the following Graph:
Implementation
Analysis
See problem 'All Root to Leaf Paths' as a prerequisite.
The general idea is to to a depth first traversal through the tree, except this time, it is not the kind of traversal one would normally expect. Typically, we visited each node a single time. To find all paths, each 'thread' of the DFS tree is unique, and should be treated as such. E.g.
A->B->C
andA->B->E
are unique, but carry the same threadA->B
.To elumate the idea of unique threads, I decided to go with an
unordered_map
that will keep track of what of the current path I have in my graph. (Just as an FYI, this map would not be needed if the graph did not contain cycles, because the algorithm would be able to exit the for loop on the instance there is no adjacent element, or the destination was found.)As I iterate through the paths, I maintain an ordered vector and push back elements. I also keep the
unordered_map
, and insert elements into it the same instances of the vector. The advantage is that I am able to maintain both order of the path, as well as a constant time lookup to detect if I need to insert the next element in. Its a trade off of space for time.Once the destination is found, I remove the latest element in the vector, as well as the the element in the map. I then return to go back to an earlier state in the traversal.
Because of how the stack is structured, on return the for loop exits and the path isn't repeated again.
It is not necessary to iterate outside the scope of
src
(e.g. NodesL
andM
), because they are guaranteed to be disconnected anyway, and in no waysrc
can connect todest
ifdest
is within a disconnected subgraph fromsrc
.
Last updated