Reputation: 18754
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.
Upvotes: 1
Views: 144
Reputation: 178411
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->A
Next, do a DFS on the original graph, again from C.
In your example it will give you Path2= C->D
Now, by reversing Path1
, and concatinating Path2
to it you will get:
reverse(Path1) + Path2 = A->B->C + C->D = A->B->C->D
Clarification - DFS is just abstraction, what you actually are doing is something similar to (pseudo code):
current <- C
list = []
while (current != null):
list.addFirst(current)
current <- u such that (u,current) is in the DataBase
current <- C
list.deleteLast() // last is C
while (current != null):
list.addLast(current)
current <- u such that (current,u) is in the DataBase
Note that finding u
both cases is a simple dictionary look up, in the first the "Target" is the key, and in the second the "Source" is the key.
Upvotes: 2