how to find all possible path between 2 nodes
Ältere Kommentare anzeigen
knowing the connectivity between nodes, how can i find the possible path between 2 nodes?
2 Kommentare
Ken Bannister
am 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
am 8 Apr. 2023
Sppose further that for some reason one or more nodes are blocked?
Akzeptierte Antwort
Weitere Antworten (1)
Walter Roberson
am 24 Apr. 2019
0 Stimmen
5 Kommentare
Elysi Cochin
am 24 Apr. 2019
Bearbeitet: Elysi Cochin
am 24 Apr. 2019
Walter Roberson
am 24 Apr. 2019
https://www.mathworks.com/help/matlab/ref/digraph.toposort.html
Guillaume
am 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
am 24 Apr. 2019
Kategorien
Mehr zu Graph and Network Algorithms finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

