在 Prolog 中使用 DFS 和状态空间的水壶问题

问题描述 投票:0回答:0

我正在使用状态空间和 dfs 解决水壶问题,水壶 1 的容量为 4,水壶 2 的容量为 3,显示使水壶 2 中有 2 的路径

% Water Jug problem using DFS in Prolog

% Define the initial state
start(jug(0,0)).

% Define the goal state
goal(jug(_,2)).

% Define the actions that can be taken
action(fill1, jug(_,Y), jug(4,Y)).
action(fill2, jug(X,_), jug(X,3)).
action(empty1, jug(_,Y), jug(0,Y)).
action(empty2, jug(X,_), jug(X,0)).
action(pour1to2, jug(X,Y), jug(X1,Y1)) :- X > 0, Y < 3, X1 is 0, Y1 is min(3, X + Y).
action(pour2to1, jug(X,Y), jug(X1,Y1)) :- Y > 0, X < 4, Y1 is 0, X1 is min(4, X + Y).

% Define the DFS algorithm
dfs(State, [], _) :- goal(State).

dfs(State, [Action|Actions], Visited) :-
    action(Action, State, State1),
    State1 \= State,
    \+ member(State1, Visited),
    dfs(State1, Actions, [State1|Visited]).`

To run the program
start(State), dfs(State, Actions, [State]).

我试过打印里面的内容

fill1
fill2
empty1
fill1
empty2
pour2to1
fill1
fill2
fill1
empty1
empty2
pour2to1
empty1
pour1to2
empty2
empty1

...但是没有意义,程序总是返回false。 谁能帮我找出问题所在?

prolog water-jug-problem
© www.soinside.com 2019 - 2024. All rights reserved.