I have data in database which is in the form of:
A -> B
C -> D
B -> C
F -> G
G -> J
X -> Z
This basically means that A goes to B, C goes to D etc. Given this data and a node (such as C) I would like to construct the complete path that C is found that is A -> B -> C -> D . I tried to do this by using a few dictionaries and recursive loops but I don’t like such a sluggish solution since there are lots of data in db. What is a better way to solve this problem ? In terms of both algorithm and the data structure ? Any ideas or hints are appreciated.
You are looking basically for DFS, but you need to do it twice – one per direction.
First do a a DFS on the reverse ‘graph’, starting from C.
In your example it will give you
Path1 = C->B->ANext, do a DFS on the original graph, again from C.
In your example it will give you
Path2= C->DNow, by reversing
Path1, and concatinatingPath2to it you will get:Clarification – DFS is just abstraction, what you actually are doing is something similar to (pseudo code):
Note that finding
uboth cases is a simple dictionary look up, in the first the “Target” is the key, and in the second the “Source” is the key.