Prolog Program for Depth First Search
mov(a,b).
mov(a,c).
mov(b,d).
mov(b,e).
mov(d,h).
mov(e,i).
mov(e,j).
mov(c,f).
mov(c,g).
mov(f,k).
go(Start, Goal) :-mov(a,c).
mov(b,d).
mov(b,e).
mov(d,h).
mov(e,i).
mov(e,j).
mov(c,f).
mov(c,g).
mov(f,k).
empty_stack(Empty_Stack_list),
stack(Start, Empty_Stack_list,Stack_list),
path(Start, Goal,Stack_list).
% path implements a depth first search in PROLOG
% Current state = goal, print out been list
path(Goal, Goal, Stack_list) :-
reverse_print_stack(Stack_list).
path(State, Goal, Stack_list) :-
mov(State, Next),
% not(unsafe(Next)),
not(member_stack(Next, Stack_list)),
stack(Next, Stack_list, New_Stack_list),
path(Next, Goal, New_Stack_list), !.
reverse_print_stack(S) :-
empty_stack(S).
reverse_print_stack(S) :-
stack(E, Rest, S),
reverse_print_stack(Rest),
write(E), nl.
empty_stack([]).
stack(Top, Stack, [Top|Stack]).
member_stack(Element, Stack) :-
member(Element,Stack).
reverse_print_stack(S) :- empty_stack(S).
reverse_print_stack(S) :-
stack(E,Rest,S),reverse_print_stack(Rest),write(E),nl.
member(H,[H|T]).
member(X,[_|T]) :-member(X,T).
No comments:
Post a Comment