Java代码回溯法解决狼羊菜过河问题
时间: 2024-02-13 16:07:52 浏览: 75
人狼羊菜过河程序JAVA
5星 · 资源好评率100%
狼羊菜过河问题是一个经典的人工智能问题,也是回溯算法的一个典型应用。下面是Java代码实现:
```java
import java.util.*;
public class WolfGoatCabbage {
// 定义狼、羊、菜、人的编号
private static final int WOLF = 0;
private static final int GOAT = 1;
private static final int CABBAGE = 2;
private static final int PERSON = 3;
// 定义船只状态
private static final int LEFT = 0;
private static final int RIGHT = 1;
// 定义状态类
private static class State {
private int[] items = new int[4];
private int boat;
public State(int wolf, int goat, int cabbage, int person, int boat) {
items[WOLF] = wolf;
items[GOAT] = goat;
items[CABBAGE] = cabbage;
items[PERSON] = person;
this.boat = boat;
}
public boolean isValid() {
if (items[WOLF] == items[GOAT] && items[WOLF] != items[PERSON]) {
return false;
}
if (items[GOAT] == items[CABBAGE] && items[GOAT] != items[PERSON]) {
return false;
}
return true;
}
public boolean isGoal() {
return items[WOLF] == RIGHT && items[GOAT] == RIGHT
&& items[CABBAGE] == RIGHT && items[PERSON] == RIGHT;
}
public List<State> getNextStates() {
List<State> nextStates = new ArrayList<State>();
int nextBoat = 1 - boat;
for (int i = 0; i < 4; i++) {
if (items[i] == boat) {
State nextState = new State(items[WOLF], items[GOAT], items[CABBAGE], items[PERSON], nextBoat);
nextState.items[i] = nextBoat;
if (nextState.isValid()) {
nextStates.add(nextState);
}
}
}
return nextStates;
}
public String toString() {
String s = "";
s += items[WOLF] == LEFT ? "W" : "-";
s += items[GOAT] == LEFT ? "G" : "-";
s += items[CABBAGE] == LEFT ? "C" : "-";
s += items[PERSON] == LEFT ? "P" : "-";
s += boat == LEFT ? " |---| " : " |---| ";
s += items[WOLF] == RIGHT ? "W" : "-";
s += items[GOAT] == RIGHT ? "G" : "-";
s += items[CABBAGE] == RIGHT ? "C" : "-";
s += items[PERSON] == RIGHT ? "P" : "-";
return s;
}
}
// 定义搜索函数
private static boolean search(State state, Set<State> visited, Stack<State> path) {
visited.add(state);
path.push(state);
if (state.isGoal()) {
return true;
}
for (State nextState : state.getNextStates()) {
if (!visited.contains(nextState)) {
if (search(nextState, visited, path)) {
return true;
}
}
}
path.pop();
return false;
}
// 定义主函数
public static void main(String[] args) {
State startState = new State(LEFT, LEFT, LEFT, LEFT, LEFT);
Set<State> visited = new HashSet<State>();
Stack<State> path = new Stack<State>();
if (search(startState, visited, path)) {
System.out.println("Solution found!");
for (State state : path) {
System.out.println(state);
}
} else {
System.out.println("Solution not found!");
}
}
}
```
该代码使用了一个状态类来表示问题状态,包括狼、羊、菜、人的位置和船只状态。使用回溯算法搜索状态空间,直到找到符合条件的状态,即所有物品和人都在对岸。在搜索过程中,使用一个集合来记录已经访问过的状态,避免重复搜索。搜索过程中,使用一个栈来记录路径,找到目标状态后输出路径即可。
阅读全文