【发布时间】:2020-05-20 15:17:15
【问题描述】:
我有一个带有多个起点和终点的方阵(比如 5x5)(比如 3 组):
最终目标是为每对点找到路径,这样就不会有路径与另一对点相交。在那个简单的例子中,可能有不止一个解,但在现实生活中,一旦你开始添加更多的点对,就会有一个唯一的解,它会填充整个矩阵,这样就不会留下任何正方形。
然而,我的第一步是为每一对点找到从一个起点到其对应终点的所有可能路径,以便我可以丢弃所有路径与另一点相交的路径。如果可能的话,我想这样做而不必求助于图论,因为 1)我对此一无所知,并且 2)它似乎没有在 Octave 中实现。
我对此进行了大量研究,发现GitHub 中的以下函数几乎完全符合我的目标,但确实依赖于图论:
function pth = pathbetweennodes(adj, src, snk, verbose)
%PATHBETWEENNODES Return all paths between two nodes of a graph
%
% pth = pathbetweennodes(adj, src, snk)
% pth = pathbetweennodes(adj, src, snk, vflag)
%
%
% This function returns all simple paths (i.e. no cycles) between two nodes
% in a graph. Not sure this is the most efficient algorithm, but it seems
% to work quickly for small graphs, and isn't too terrible for graphs with
% ~50 nodes.
%
% Input variables:
%
% adj: adjacency matrix
%
% src: index of starting node
%
% snk: index of target node
%
% vflag: logical scalar for verbose mode. If true, prints paths to
% screen as it traverses them (can be useful for larger,
% time-consuming graphs). [false]
%
% Output variables:
%
% pth: cell array, with each cell holding the indices of a unique path
% of nodes from src to snk.
% Copyright 2014 Kelly Kearney
我的问题是尝试计算邻接矩阵。不熟悉图论,我有点理解邻接矩阵的概念,但在实际生成所述矩阵时不知所措。
如果我分别对待每一对并将其他占用的方格视为“禁区”,那么每个场景我将有 25 - 4 = 21 个节点,并且我可以在纸上手动写下边缘,但我没有不知道如何编码?有人可以帮忙吗?
如果我们使用上面的示例并按行对节点进行排序,考虑到蓝色的点对,我们会得到类似的结果,目标是从节点 1 到节点 17(反之亦然,没有涉及方向性):
1 2 3 4 5
6 7 8
9 10 11 12 13
14 15 16 17
18 19 20 21
边缘是有效的移动(垂直或水平,无对角线),例如:
1 - 2
2 - 1
2 - 3
2 - 6
3 - 2
3 - 4
etc...
你如何从这个到一些代码?
当然,如果有更好的方法来解决这个问题,我愿意接受任何建议。就问题的规模而言,它可以达到一个 10x10 的网格,具有 10 对起点/终点,即 82 个节点。
【问题讨论】:
标签: matrix octave graph-theory adjacency-matrix