【问题标题】:search all paths and the shortest path for a graph - Prolog搜索图的所有路径和最短路径 - Prolog
【发布时间】:2010-04-01 22:22:06
【问题描述】:

我的 turbo prolog 代码在我的代码中存在问题,它在 2 个节点之间的图中搜索所有路径和最短路径。 我遇到的问题是测试节点是否在列表中(正好在成员的子句中)

           1    ---- b ----   3
           ---       |        ---
        ---          |             -----
      a              |5                  d
        ---          |             -----
            ---      |         ---
             2  ---  |     ---   4
                  -- c  --

for example we have for b--->c 
([b,c],5) , ([b,a,c],3) and ([b,d,c],7) : possible paths.
([b,a,c],3) : the shortest path.

这是我的代码:

DOMAINS
    list=Symbol *

PREDICATES
    distance(Symbol, Symbol)
    path1(Symbol, Symbol, list, integer)
    path(Symbol, Symbol,list, list, integer)
    distance(Symbol, list, integer)
    member(Symbol, list)
    shortest(Symbol, Symbol, list, integer)

CLAUSES
    distance(a, b, 1).
    distance(a, c, 2).
    distance(b, d, 3).
    distance(c, d, 4).
    distance(b, c, 5).
    distance(b, a, 1).
    distance(c, a, 2).
    distance(d, b, 3).
    distance(d, c, 4).
    distance(c, b, 5).

    member(X, [X|T]).
    member(X, [Y|T]) :- member(X, T).

    absent(X, L) :-
        member(X, L),
        !,
        fail.
    absent(_, _).

    /* find all paths */
    path1(X, Y, L, C) :- path(X, Y, L, I, C).
    path(X, X, [X], I, C) :- absent(X, I).
    path(X, Y, [X|R], I, C) :-
        distance(X, Z, A),
        absent(Z, I),
        path(Z, Y, R, [X|I], C1),
        C = C1 + A
        .

    /* to find the shortest path */
    shortest(X, Y, L, C) :-
        path(X, Y, L, C),
        path(X, Y, L1, C1),
        C < C1.

【问题讨论】:

  • 你没有说明你的问题是什么。

标签: prolog graph-theory shortest-path turbo-prolog


【解决方案1】:

这显示了最短路径和它的权重:

edge(a,b,6).
edge(a,c,1).
edge(b,d,5).
edge(c,e,4).
edge(c,f,1).
edge(d,h,3).
edge(e,h,7).
edge(f,g,2).
edge(g,h,1).

path(X,Y,M,[Y]) :- edge(X,Y,M).
path(X,Y,P,[Z|T]) :- edge(X,Z,M),path(Z,Y,N,T),
            P is M+N.

pravilo(X,Y,Z) :-  assert(min(100)),assert(minpath([])),!,
                path(X,Y,K,PATH1),
                (min(Z),K<Z,
                retract(min(Z));assert(min(K))),
                minpath(Q),retract(minpath(Q)),
                assert(minpath([X|PATH1])),
                fail.

?- pravilo(a,h,X);
    write("Minimal Path:"),
    minpath(PATH),
    write(PATH),
    nl,
    write("Path weight:"),
    min(Z),
    write(Z).

【讨论】:

    【解决方案2】:

    在不知道实际问题是什么的情况下,我至少可以建议也许 shortest() 和 path() 应该采用一个最大长度参数来缩短搜索。

    另外,shortest() 找不到最短路径。它为每一对可能的路径找到每对中最短的路径。

    【讨论】:

    • 好的,我知道你能提出解决这个问题的方法吗,谢谢!因为我尝试但没有解决方案!!!
    猜你喜欢
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多