how to find all possible path between 2 nodes
이전 댓글 표시
knowing the connectivity between nodes, how can i find the possible path between 2 nodes?
댓글 수: 2
Ken Bannister
2023년 4월 8일
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
2023년 4월 8일
Sppose further that for some reason one or more nodes are blocked?
채택된 답변
추가 답변 (1개)
Walter Roberson
2019년 4월 24일
0 개 추천
댓글 수: 5
Elysi Cochin
2019년 4월 24일
편집: Elysi Cochin
2019년 4월 24일
Walter Roberson
2019년 4월 24일
https://www.mathworks.com/help/matlab/ref/digraph.toposort.html
Guillaume
2019년 4월 24일
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
2019년 4월 24일
카테고리
도움말 센터 및 File Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

