graphshortestpath function visiting all nodes

11 次查看(过去 30 天)
Hi,
Is there a way I can manipulate this function in order to force the path include all nodes? I mean, how can I change the code in order to include each node to find the shortest path , but with the constrain that we must visit all nodes?
Thank you in advance
  3 个评论
Jason
Jason 2018-3-6
编辑:Walter Roberson 2018-3-6
W
= [5 1 5 4 6 1 1 4 7 2 6 7 3 2 1 2 3 8 2 8];
DG = sparse([1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6],[2 3 1 3 4 5 1 2 4 5 2 3 5 6 2 3 4 6 4 5],W)
h = view(biograph(DG,[],'ShowWeights','on'))
[dist,path,pred] = graphshortestpath(DG,1,6)
set(h.Nodes(path),'Color',[0 1 1])
edges = getedgesbynodeid(h,get(h.Nodes(path),'ID'));
set(edges,'LineColor',[0 0 1])
set(edges,'LineWidth',2)
I am implementing the above code, as I understand this function examines the shortest path among all the nodes.
I want to manipulate the code in order to visit all the nodes and outputs a graph that has visited all the nodes with the minimum distance.
Jason
Jason 2018-3-6
Plus, I cannot visit the same node twice for example 1-2-3-1-4.

请先登录,再进行评论。

采纳的回答

Jason
Jason 2018-3-19
编辑:Walter Roberson 2018-3-19

更多回答(2 个)

Christine Tobler
Christine Tobler 2018-3-6
As Steve Lord has said, in general this is an NP-complete problem, so could become quite expensive. For the 6-node graph you are looking at, this is easy to compute using an exhaustive search (I will use the graph object instead of the bioinfo variants here):
W = [5 1 5 4 6 1 1 4 7 2 6 7 3 2 1 2 3 8 2 8];
DG = sparse([1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6],...
[2 3 1 3 4 5 1 2 4 5 2 3 5 6 2 3 4 6 4 5],W);
g = graph(DG);
% Construct all possible ways that we could traverse all nodes, starting at
% node 1 and ending at node 6:
paths = perms(2:5);
paths = [ones(size(paths, 1), 1) paths 6*ones(size(paths, 1), 1)];
% Check if a path is feasible (edges exist between all node pairs), and how
% long it is
dist = NaN(size(paths, 1), 1);
for ii=1:size(paths, 1)
path = paths(ii, :);
edgeID = findedge(g, path(1:end-1), path(2:end));
if all(edgeID ~= 0)
dist(ii) = sum(g.Edges.Weight(edgeID));
end
end
[~, id] = min(dist)
paths(id, :)
p = plot(g, 'EdgeLabel', g.Edges.Weight);
highlight(p, paths(id, :), 'EdgeColor', 'red')
  28 个评论
Jason
Jason 2018-3-19
编辑:Jason 2018-3-19
Anyway, can you at least show me how to create a matrix with ones in the last column, something like
paths = [ones(size(paths, 1), 1) paths];
but not in the first column. Namely, add ones in the last column of this matrix.
thank you
Steven Lord
Steven Lord 2018-3-19
Move the ones call after the paths variable rather than before.

请先登录,再进行评论。


Steven Lord
Steven Lord 2018-3-6
So you want the shortest Hamiltonian path? That may be very hard.

类别

Help CenterFile Exchange 中查找有关 Graph and Network Algorithms 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by