Shortest path constrained to use specific nodes

조회 수: 2 (최근 30일)
Tejas
Tejas 2021년 4월 3일
편집: Matt J 2021년 4월 3일
Let's say I have a simple graph:
G = graph([1,2,3,4,5],[2,3,4,5,1]);
I want to find the shortest path from 1 to 3. The shortestpath function would give me 1-2-3. But in my case, I have a list of nodes that I can travel on:
nodes = [1,3,4,5];
How can I find the shortest path between any two nodes in the graph that only takes the nodes in that list (which will be 1-5-4-3 in this case)?

답변 (3개)

Matt J
Matt J 2021년 4월 3일
편집: Matt J 2021년 4월 3일
Why not just analyze a subgraph with the inadmissible nodes removed:
cut=setdiff(1:numnodes(G),nodes);
Gsub=rmnodes(G,cut);

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 4월 3일
Here is an easy solution:
shortestpath(G, 1,3) % Shortest path between 1 and 3
Good luck.
  댓글 수: 1
Tejas
Tejas 2021년 4월 3일
That does not answer my question, since it'll give 1-2-3, and I cannot use 2.

댓글을 달려면 로그인하십시오.


Tejas
Tejas 2021년 4월 3일
Okay, I realised if I assign weights like:
G = graph([1,2,3,4,5],[2,3,4,5,1],[Inf,1,1,1,1]);
Then I do get
shortestpath(G,1,3)
ans =
1 5 4 3
I don't have any other purpose for weights so I can use them in this way.

카테고리

Help CenterFile Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by