开始和结束点列表的基本非加权寻路

时间:2012-11-27 06:19:26

标签: php mysql

我正在制作一个旅游项目,我遇到了问题。我创建了一个数据库:

ID  Source   Destination

1     C1         C2
2     C3         c4
3     C3         C5
4     C4         C6
5     C8         C9
6     C2         C3

当我从C1-> C6进行巡视时,它应该遵循路径c1-> c2-> c3-> c4-> c6。但是当通过查询检索时,我在到达c3时遇到了冲突:还有另一个C3-> c5。

我该如何克服这个问题?

首先我通过检查mysql将c1作为源代码 从那个我到达目的地的目的地作为来源检查相关的目的地

2 个答案:

答案 0 :(得分:1)

1)您可以通过将数据存储到树中来解决,并使用算法到达目的地:

enter image description here

2)使用数组和递归的简单解决方案:

这里复杂的部分只是带来“所提到的来源和目的地的必需数据”,即留下c8-> c9

我一直努力带来foll数据。但是,你可以继续这样做:     $ destination ['c1'] ='c2';     $ destination ['c3'] [] ='c4';     $ destination ['c4'] ='c6';     $ destination ['c2'] ='c3';

$route = array();
$int = 0;

function route_to($route,$source_statn, $dest_statn) {
    global $int, $destination,$path;

    if ($source_statn != '' && $dest_statn != '') {
        if ($destination[$source_statn] == $dest_statn) {
            $route[++$int] = "$source_statn -> {$destination[$source_statn]}";

            $path = $route;
            return $path;
        } else {
            if (is_array($destination[$source_statn])) {
                foreach ($destination[$source_statn] as $each) {
                    $route[++$int] = "$source_statn -> $each";
                    route_to($route,$each, $dest_statn);
                }
            } else {
                if($destination[$source_statn] != ''){
                    $route[++$int] = "$source_statn -> {$destination[$source_statn]}";
                }
                route_to($route,$destination[$source_statn], $dest_statn);
            }
        }
    }
}

route_to($route,'c1','c6');

echo '<pre>path';
print_r($path);
echo '</pre>';

--------- O / P -----------

Array
(
    [1] => c1 -> c2
    [2] => c2 -> c3
    [3] => c3 -> c4
    [4] => c4 -> c6
)

答案 1 :(得分:1)

尝试:

CREATE TABLE test (
  ID INTEGER NOT NULL,
  SOURCE CHAR(2) NOT NULL,
  DESTINATION CHAR(2) NOT NULL
);

INSERT INTO test VALUES (1, 'C1', 'C2');
INSERT INTO test VALUES (2, 'C3', 'C4');
INSERT INTO test VALUES (3, 'C3', 'C5');
INSERT INTO test VALUES (4, 'C4', 'C6');
INSERT INTO test VALUES (5, 'C8', 'C9');
INSERT INTO test VALUES (6, 'C2', 'C3');

然后:

SELECT
  CONCAT_WS(
    '->',
    A.SOURCE,
    A.DESTINATION,
    B.DESTINATION,
    C.DESTINATION,
    D.DESTINATION
  )
FROM test A
LEFT JOIN test B ON B.SOURCE = A.DESTINATION
LEFT JOIN test C ON C.SOURCE = B.DESTINATION
LEFT JOIN test D ON D.SOURCE = C.DESTINATION
WHERE
  A.SOURCE = 'C1'
  AND 'C6' IN (A.DESTINATION, B.DESTINATION, C.DESTINATION, D.DESTINATION);

给出了:

C1->C2->C3->C4->C6

请注意,此示例仅提供最大深度为4的路径,但您可以轻松扩展此路径。您还将获得所有可能的路径(如果有多个路径)。所以你需要决定选择哪一个。