how to find all possible path between 2 nodes
Mostrar comentarios más antiguos
knowing the connectivity between nodes, how can i find the possible path between 2 nodes?
2 comentarios
Ken Bannister
el 8 de Abr. de 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
el 8 de Abr. de 2023
Sppose further that for some reason one or more nodes are blocked?
Respuesta aceptada
Más respuestas (1)
Walter Roberson
el 24 de Abr. de 2019
0 votos
5 comentarios
Elysi Cochin
el 24 de Abr. de 2019
Editada: Elysi Cochin
el 24 de Abr. de 2019
Walter Roberson
el 24 de Abr. de 2019
https://www.mathworks.com/help/matlab/ref/digraph.toposort.html
Guillaume
el 24 de Abr. de 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
el 24 de Abr. de 2019
Categorías
Más información sobre Graph and Network Algorithms en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

