Suppose we have undirected, weighted graph. Our task is to find all paths beetween two vertices (source and destination) which total cost equal = N. I think it can be done with modified Dijkstra's algorithm combined with BFS or DFS, but I have no idea how implement such thing. Thanks for any help.
Asked
Active
Viewed 480 times
4

TemplateRex
- 69,038
- 19
- 164
- 304

IlanMosheShimsoni
- 41
- 3
-
Equal, or at most equal? If it is the former, the problem is NP-hard via reduction to the hamiltonian path problem. – John Dvorak Jan 24 '13 at 12:35
-
Then your problem is NP-hard (NP-complete or even worse), and I can't seem to find a NP solution to _count_ the paths. – John Dvorak Jan 24 '13 at 12:38
-
Note there can be up to `(n-2)!` solutions (complete graph, all edges equal in length, a hamiltonian path is desired), so enumeration will be slow as hell. – John Dvorak Jan 24 '13 at 12:41
-
my goal isnt count the path, is to count the total path's value that be equel to N – IlanMosheShimsoni Jan 24 '13 at 12:43
-
You want to enumerate the paths whose length is `N`, right? There could be _many_ of them. – John Dvorak Jan 24 '13 at 12:44
-
yes, this is my goal. (our graph has maximum 30 Vertex) thanks – IlanMosheShimsoni Jan 24 '13 at 12:54
1 Answers
3
Assuming you have a framework / library to create a graph data structure and to traverse it, you could do a backtracking depth-first search with an early return if you cross your resource constraint. In pseudo-code:
void DFS(Vertex current, Vertex goal, List<Vertex> path, int money_left) {
// oops
if (money_left < 0)
return;
// avoid cycles
if (contains(path, current)
return;
// got it!
if (current == goal)) {
if (money_left == 0)
print(path);
return;
}
// keep looking
children = successors(current); // optionally sorted from low to high cost
for(child: children)
DFS(child, add_path(path, child), money_left - cost(child));
}
and you can then call it as DFS(start, goal, List<Vertex>(empty), N)

TemplateRex
- 69,038
- 19
- 164
- 304
-
-
@Patashu tnx, updated. Without that clause, it would find all paths with `cost <= N` – TemplateRex Jan 24 '13 at 22:00
-
It should still return if current == goal but money_left != 0, so it doesn't go on a pointless search past the goal – Patashu Jan 24 '13 at 22:02
-
@Patashu good to see that in your time zone you are not almost asleep ;-) updated. – TemplateRex Jan 24 '13 at 22:06