Breadth First Search in Prolog

后端 未结 1 746
野趣味
野趣味 2021-01-06 06:45

I\'m new to Prolog and currently implementing DFS (depth-first search) and BFS (breadth-first search) algorithms. My DFS works fine as the code below, but the BFS is termina

相关标签:
1条回答
  • 2021-01-06 07:02

    First, the usual notion of s(A,B) is just like your connect2(A,B,_).

    You should make your interface predicates explicit:

    depth_first( Start, Goal, Path):-
        depth_first( Start, Goal, [Start], Path).
    

    Maintaining a queue in BFS is not complicated at all. Instead of Visited, have VisitedLists queue (pop from front; add at end; thus FIFO):

    consed( A, B, [B|A]).
    
    bfs( Goal, [Visited|Rest], Path) :-                     % take one from front
        Visited = [Start|_],            
        Start \== Goal,
        findall( X,
            ( connected2(X, Start, _), \+ member(X, Visited) ),
            [T|Extend]),
        maplist( consed(Visited), [T|Extend], VisitedExtended),      % make many
        append( Rest, VisitedExtended, UpdatedQueue),       % put them at the end
        bfs( Goal, UpdatedQueue, Path ).
    

    When the goal is reached, Path is instantiated:

    bfs(Goal, [[Goal|Visited]|_], Path):- 
        reverse([Goal|Visited], Path).
    

    The interface call needs to be adjusted correspondingly. It should be

    breadth_first( Start, Goal, Path):- bfs( Goal, [[Start]], Path).
    

    later note: repeated appending of course causes quadratic slowdown, so for efficiency this should be re-written with difference lists (also a straightforward task).

    0 讨论(0)
提交回复
热议问题