how to find all possible path between 2 nodes
Show older comments
knowing the connectivity between nodes, how can i find the possible path between 2 nodes?
2 Comments
Ken Bannister
on 8 Apr 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
on 8 Apr 2023
Sppose further that for some reason one or more nodes are blocked?
Accepted Answer
More Answers (1)
Walter Roberson
on 24 Apr 2019
0 votes
5 Comments
Elysi Cochin
on 24 Apr 2019
Edited: Elysi Cochin
on 24 Apr 2019
Walter Roberson
on 24 Apr 2019
https://www.mathworks.com/help/matlab/ref/digraph.toposort.html
Guillaume
on 24 Apr 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
on 24 Apr 2019
Categories
Find more on Graph and Network Algorithms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
