how to find all possible path between 2 nodes
Afficher commentaires plus anciens
knowing the connectivity between nodes, how can i find the possible path between 2 nodes?
2 commentaires
Ken Bannister
le 8 Avr 2023
An interesting variation on this question is how to find the shortest path to visit each node just once. I suppose in this case one would have to loop through, using each node as a starting point.
Ken Bannister
le 8 Avr 2023
Sppose further that for some reason one or more nodes are blocked?
Réponse acceptée
Plus de réponses (1)
Walter Roberson
le 24 Avr 2019
0 votes
5 commentaires
Elysi Cochin
le 24 Avr 2019
Modifié(e) : Elysi Cochin
le 24 Avr 2019
Walter Roberson
le 24 Avr 2019
https://www.mathworks.com/help/matlab/ref/digraph.toposort.html
Guillaume
le 24 Avr 2019
toposort does not give you all paths between two nodes. It only gives you an ordering that makes searching the graph easier.
You could use my algorithm in Walter's first link to compute all paths of the graph, then only keep the paths that contain the two nodes you care about and finally remove duplicate leftovers. Although it would work, it wouldn't be particularly efficient since you'll be computing a lot of useless paths. You could probably solve your problem using bfsearch or dfsearch.
%g: a DAG created with the digraph function
%s: start node
%e: end node
%eg:
edges = [1,2;1,5;2,3;2,3;2,14;2,18;3,16;5,6;5,14;5,15];
g = digraph(edges(:, 1), edges(:, 2));
s = 1;
e = 14;
%get all paths
allpaths = getpaths(g);
%only keep those paths that link s and e and only that part of the path between s and e (or e and s)
keep = false(size(allpath));
for pidx = 1:numel(allpaths)
[found, where] = ismember([s, e], allpaths{pidx});
if all(found)
keep(pidx) = true;
allpaths{pidx} = allpaths{pidx}(min(where):max(where)); %only keep part of the path between the two node
end
end
selectedpaths = allpaths(keep)
%after pruning the path, we may have duplicates that need removing
%this part left as 'an exercice to the reader'
Elysi Cochin
le 24 Avr 2019
Catégories
En savoir plus sur Graph and Network Algorithms dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

